diff --git a/aks-node-controller/README.md b/aks-node-controller/README.md index 0dfadc62831..7c8804ac8bd 100644 --- a/aks-node-controller/README.md +++ b/aks-node-controller/README.md @@ -94,21 +94,45 @@ the provisioning config in CustomData; the automatic size fallback uses the same config-only payload. Leaving the new flag false preserves legacy, Phase 2, and Phase 2.5 behavior. -The VHD launcher calls `init-cloud` before acquiring a hotfix. ANC uses the NBC -command when present, otherwise AKSNodeConfig, and records successful initialization -in `/run/aks/init-aks-cloud.done` so provisioning does not repeat it. Older NBC -commands that do not support this marker retain the previous hotfix ordering. On -failure, the launcher skips acquisition and provisioning retries initialization. - -For scriptless nodes using early initialization, `init-aks-cloud.sh` is not -hotfixable for that initial run: it runs before hotfix acquisition, and the marker -is not script-version-aware. Fixes to early initialization require rebuilding the -VHD and provisioning from the rebuilt image; replacing the script in a hotfix does -not rerun it after a successful early initialization. - -The plan is to move the initialization logic into ANC in Go to make it hotfixable -again. That future design must safely apply updated initialization logic after -hotfix acquisition while preserving legacy shell-based provisioning. +### Azure cloud initialization + +The VHD launcher calls `init-cloud` before acquiring a hotfix, so custom and +sovereign clouds can reach RepoDepot. ANC uses the NBC command when present, +otherwise AKSNodeConfig, and records successful initialization with an empty +`/run/aks/init-aks-cloud.done` marker so provisioning does not run +`init-aks-cloud.sh` again. Older NBC commands that do not support this marker +retain the previous hotfix ordering. On failure, no marker is written, the +launcher skips acquisition, and provisioning runs `init-aks-cloud.sh` as before. + +With NBC, `init-cloud` runs `init-aks-cloud.sh`. With AKSNodeConfig alone, it runs +the native initialization below instead. Either way, early initialization runs the +VHD binary before hotfix acquisition, so it is not hotfixable: fixes require +rebuilding the VHD, and a hotfix does not rerun initialization after it succeeded. +Detecting hotfixes that change initialization, and safely rerunning it after +acquisition, are left to follow-up changes. + +#### Native Azure cloud initialization + +`init-cloud` uses two paths based on input: +- **AKSNodeConfig only** (`--provision-config`): initializes Azure cloud (certificates + RepoDepot) **in Go** +- **NBC present** (`--nbc-cmd`): runs shell `init-aks-cloud.sh` (preserves existing behavior) + +Like the shell version, initialization: (1) installs certificates, (2) configures repositories, (3) schedules refresh. Legacy Mariner is not supported by the Go path. + +Regions starting with `ussec` or `usnat` use legacy certificate endpoints. Other regions check WireServer opt-in before downloading RCV1P certificates. Behavior mirrors the shell: only `true` enables opt-in, and individual certificate download failures are logged and skipped (but are non-fatal). Downloaded certificates are passed to system trust-store tools without additional validation. + +Eligible nodes schedule daily 19:00 certificate refresh via cron (Ubuntu/Azure Linux) or systemd (Flatcar/ACL). Refresh uses the running ANC binary (which is the VHD binary during init-cloud, since it runs before hotfix acquisition). + +Repository configuration is independent of certificate opt-in. Ubuntu sources, Microsoft keyrings, and Azure Linux repositories are configured when a repository endpoint is present. Cache refresh retries up to 10 times and reports failures in guest-agent events, matching the shell's best-effort approach. + +Cloud commands run in their own process groups with a two-minute timeout, or +the caller's earlier cancellation. Cancellation kills the entire group. A +five-second `WaitDelay` bounds output draining after cancellation or command +exit, including when a descendant leaves the group but retains an output pipe. + +Native initialization and periodic refresh emit guest-agent events through +`EventLogger` using `CloudInitialization`, `CloudRepositoryInitialization`, and +`CloudCertificateRefresh` task suffixes, alongside the existing ANC logs. ### Validating and normalizing AKSNodeConfig diff --git a/aks-node-controller/app.go b/aks-node-controller/app.go index 3e82a76ec33..a4d19a9498d 100644 --- a/aks-node-controller/app.go +++ b/aks-node-controller/app.go @@ -108,6 +108,9 @@ type App struct { // grpcDialContext overrides how the gRPC LPS client dials, letting tests point the client at // an in-process (bufconn) server. When nil, the real TLS dial to the apiserver front is used. grpcDialContext func(ctx context.Context, target string) (net.Conn, error) + // Cloud initialization overrides keep init-cloud and certificate refresh tests independent of the host. + initializeNativeCloud func(context.Context, cloudInitConfig) error + refreshCloudCertificates func(context.Context, string) error } // provision.json values are emitted as strings by the shell jq invocation. @@ -188,6 +191,19 @@ func (a *App) Run(ctx context.Context, args []string) int { return nil }, }, + { + Name: "refresh-cloud-certificates", + Usage: "Refresh Azure cloud CA certificates without configuring repositories", + Flags: []cli.Flag{ + &cli.StringFlag{Name: "location", Required: true, Usage: "Azure region used to select the certificate endpoint"}, + }, + Action: func(ctx context.Context, cmd *cli.Command) error { + if cmd.Args().Len() != 0 { + return fmt.Errorf("unexpected refresh-cloud-certificates arguments: %s", strings.Join(cmd.Args().Slice(), " ")) + } + return a.runCloudCertificateRefresh(ctx, cmd.String("location")) + }, + }, { Name: "download-hotfix", Usage: "Download the requested hotfix binary", diff --git a/aks-node-controller/cloud_certificate_store.go b/aks-node-controller/cloud_certificate_store.go new file mode 100644 index 00000000000..91ef7fbd653 --- /dev/null +++ b/aks-node-controller/cloud_certificate_store.go @@ -0,0 +1,128 @@ +package main + +import ( + "bytes" + "context" + "crypto/x509" + "encoding/pem" + "errors" + "fmt" + "log/slog" + "os" + "path/filepath" + "sort" + "strings" + + "github.com/Azure/agentbaker/aks-node-controller/config" +) + +func (c *cloudInitializer) clearCertificateCache() { + directory := c.path("/root/AzureCACertificates") + if err := os.MkdirAll(directory, 0o755); err != nil { + slog.Warn("could not create Azure cloud certificate cache", "error", err) + return + } + entries, err := os.ReadDir(directory) + if err != nil { + slog.Warn("could not read Azure cloud certificate cache", "error", err) + return + } + // Certificate downloads are written directly here as files, without subdirectories. + for _, entry := range entries { + if err := os.Remove(filepath.Join(directory, entry.Name())); err != nil { + slog.Warn("could not remove cached Azure cloud certificate", "name", entry.Name(), "error", err) + } + } +} + +func publicCloudCertificates(data []byte) ([]byte, error) { + var result bytes.Buffer + for { + block, rest := pem.Decode(data) + if block == nil { + break + } + data = rest + if block.Type != "CERTIFICATE" { + continue + } + if _, err := x509.ParseCertificate(block.Bytes); err != nil { + return nil, fmt.Errorf("invalid CA certificate: %w", err) + } + if err := pem.Encode(&result, &pem.Block{Type: "CERTIFICATE", Bytes: block.Bytes}); err != nil { + return nil, err + } + } + if result.Len() == 0 { + return nil, errors.New("response contains no PEM certificates") + } + return result.Bytes(), nil +} + +func (c *cloudInitializer) installCertificates(ctx context.Context, platform cloudPlatform, certificates map[string][]byte) error { + destination, update := "/usr/local/share/ca-certificates", "update-ca-certificates" + switch platform.ID { + case config.OSReleaseIDAzureLinux, config.OSReleaseIDAzureContainerLinux: + destination, update = "/etc/pki/ca-trust/source/anchors", "update-ca-trust" + case config.OSReleaseIDFlatcar: + destination = "/etc/ssl/certs" + } + names := make([]string, 0, len(certificates)) + for name := range certificates { + names = append(names, name) + } + sort.Strings(names) + installed := 0 + for _, name := range names { + data := certificates[name] + if !strings.HasSuffix(name, ".crt") { + continue + } + targetName := name + if platform.ID == config.OSReleaseIDFlatcar { + targetName = strings.TrimSuffix(name, ".crt") + ".pem" + } + if err := c.writeFile(filepath.Join(destination, targetName), data); err != nil { + return err + } + installed++ + if os.Getenv("AKS_CLOUD_LOG_CERTIFICATES") == "true" { + public, err := publicCloudCertificates(data) + if err != nil { + slog.Warn("could not decode public Azure cloud CA certificates for logging", "name", name, "error", err) + continue + } + slog.Info("Azure cloud public CA certificate", "name", name, "certificate", string(public)) + } + } + if installed == 0 { + return errors.New("no *.crt files in Azure cloud certificate cache to install") + } + if _, err := c.command(ctx, nil, update); err != nil { + return err + } + if platform.ID == config.OSReleaseIDUbuntu { + return c.copyOpenSSLBundle() + } + return nil +} + +func (c *cloudInitializer) copyOpenSSLBundle() error { + source, target := c.path("/etc/ssl/certs/ca-certificates.crt"), c.path("/usr/lib/ssl/cert.pem") + sourceInfo, err := os.Stat(source) + if err != nil { + return err + } + targetInfo, err := os.Stat(target) + if err == nil && os.SameFile(sourceInfo, targetInfo) { + return nil + } + if err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + data, err := os.ReadFile(source) + if err != nil { + return err + } + return c.writeFile("/usr/lib/ssl/cert.pem", data) +} diff --git a/aks-node-controller/cloud_certificate_store_behavior_test.go b/aks-node-controller/cloud_certificate_store_behavior_test.go new file mode 100644 index 00000000000..ca81b311f25 --- /dev/null +++ b/aks-node-controller/cloud_certificate_store_behavior_test.go @@ -0,0 +1,104 @@ +package main + +import ( + "encoding/pem" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/Azure/agentbaker/aks-node-controller/config" +) + +func TestCloudCertificateStorePlatformInstallation(t *testing.T) { + for _, tc := range []struct{ id, target, command string }{ + {config.OSReleaseIDUbuntu, "/usr/local/share/ca-certificates/root.crt", "update-ca-certificates"}, + {config.OSReleaseIDAzureLinux, "/etc/pki/ca-trust/source/anchors/root.crt", "update-ca-trust"}, + {config.OSReleaseIDAzureContainerLinux, "/etc/pki/ca-trust/source/anchors/root.crt", "update-ca-trust"}, + {config.OSReleaseIDFlatcar, "/etc/ssl/certs/root.pem", "update-ca-certificates"}, + } { + t.Run(tc.id, func(t *testing.T) { + c := newTestCloudInitializer(t, "ID="+tc.id+"\n") + platform, err := c.platform() + require.NoError(t, err) + var commands []string + c.run = func(cmd *exec.Cmd) error { + commands = append(commands, cmd.Args[0]) + return nil + } + payload := []byte("unparsed certificate payload\n") + require.NoError(t, c.installCertificates(t.Context(), platform, map[string][]byte{ + "root.crt": payload, + "skip.cer": []byte("ignored"), + })) + got, err := os.ReadFile(c.path(tc.target)) + require.NoError(t, err) + require.Equal(t, payload, got) + require.Equal(t, []string{tc.command}, commands) + _, err = os.Stat(c.path(filepath.Join(filepath.Dir(tc.target), "skip.cer"))) + require.ErrorIs(t, err, os.ErrNotExist) + if tc.id == config.OSReleaseIDUbuntu { + bundle, err := os.ReadFile(c.path("/usr/lib/ssl/cert.pem")) + require.NoError(t, err) + require.Equal(t, "system-ca-bundle", string(bundle)) + } + }) + } +} + +func TestCloudCertificateStoreRejectsMissingCRTFiles(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + c.run = func(*exec.Cmd) error { + t.Fatal("empty certificate sets must not invoke trust-store tools") + return nil + } + err := c.installCertificates(t.Context(), cloudPlatform{ID: config.OSReleaseIDUbuntu}, map[string][]byte{ + "root.cer": []byte("ignored"), + }) + require.ErrorContains(t, err, "no *.crt files") +} + +func TestCloudCertificateStoreClearsOnlyFlatStagingFiles(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + for _, name := range []string{"root.crt", ".hidden.crt", "nested/keep.crt"} { + require.NoError(t, c.writeFile("/root/AzureCACertificates/"+name, []byte(name))) + } + installed := "/usr/local/share/ca-certificates/installed.crt" + require.NoError(t, c.writeFile(installed, []byte("installed CA"))) + c.clearCertificateCache() + for _, name := range []string{"root.crt", ".hidden.crt"} { + _, err := os.Stat(c.path("/root/AzureCACertificates/" + name)) + require.ErrorIs(t, err, os.ErrNotExist) + } + for _, name := range []string{"/root/AzureCACertificates/nested/keep.crt", installed} { + _, err := os.Stat(c.path(name)) + require.NoError(t, err) + } +} + +func TestCloudCertificateStoreLoggingPreservesRawPayload(t *testing.T) { + t.Setenv("AKS_CLOUD_LOG_CERTIFICATES", "true") + logs := installLogCapturer(t) + c := newTestCloudInitializer(t, "ID=azurelinux\n") + payload := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: []byte("not-a-real-private-key")}) + payload = append(payload, cloudTestCertificate(t)...) + require.NoError(t, c.installCertificates(t.Context(), cloudPlatform{ID: config.OSReleaseIDAzureLinux}, map[string][]byte{ + "root.crt": payload, + })) + got, err := os.ReadFile(c.path("/etc/pki/ca-trust/source/anchors/root.crt")) + require.NoError(t, err) + require.Equal(t, payload, got) + found := false + for _, record := range logs.getRecords() { + for _, value := range record.Attrs { + require.NotContains(t, value, "PRIVATE KEY") + if strings.Contains(value, "BEGIN CERTIFICATE") { + found = true + } + } + } + require.True(t, found) +} diff --git a/aks-node-controller/cloud_certificate_store_test.go b/aks-node-controller/cloud_certificate_store_test.go new file mode 100644 index 00000000000..f8f37c6198d --- /dev/null +++ b/aks-node-controller/cloud_certificate_store_test.go @@ -0,0 +1,18 @@ +package main + +import ( + "os" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestCloudCertificateUbuntuBundleSymlink(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + require.NoError(t, os.MkdirAll(c.path("/usr/lib/ssl"), 0o755)) + require.NoError(t, os.Symlink(c.path("/etc/ssl/certs/ca-certificates.crt"), c.path("/usr/lib/ssl/cert.pem"))) + require.NoError(t, c.copyOpenSSLBundle()) + info, err := os.Lstat(c.path("/usr/lib/ssl/cert.pem")) + require.NoError(t, err) + require.NotZero(t, info.Mode()&os.ModeSymlink) +} diff --git a/aks-node-controller/cloud_certificate_transport.go b/aks-node-controller/cloud_certificate_transport.go new file mode 100644 index 00000000000..1c41146f914 --- /dev/null +++ b/aks-node-controller/cloud_certificate_transport.go @@ -0,0 +1,179 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "maps" + "net/http" + "path/filepath" + "strings" + "time" + + "github.com/Azure/agentbaker/aks-node-controller/common" +) + +const cloudRequestAttempts = 10 + +func (c *cloudInitializer) requestCertificates(ctx context.Context, path string) ([]byte, error) { + attempt := 0 + delay, nextDelay := 3*time.Second, time.Duration(0) + return common.RetryFetch(ctx, cloudRequestAttempts, nil, func(ctx context.Context) ([]byte, error) { + if attempt > 0 { + if err := c.wait(ctx, nextDelay); err != nil { + return nil, err + } + } + attempt++ + req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.wireEndpoint+path, nil) + if err != nil { + return nil, err + } + nextDelay = delay + resp, err := c.wireClient.Do(req) + if err != nil { + return nil, err + } + body, err := readCloudResponse(resp) + if err != nil { + return nil, err + } + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + return body, nil + } + if resp.StatusCode == http.StatusForbidden && bytes.Contains(body, []byte("RequestRateLimitExceeded")) { + delay *= 2 + } + return nil, fmt.Errorf("WireServer certificate request %s returned HTTP %d", path, resp.StatusCode) + }) +} + +func certificatePackagePath(kind, extension string) string { + // Match the shell's raw query values without assuming WireServer's decoding contract. + return "/machine?comp=acmspackage&type=" + kind + "&ext=" + extension +} + +func validCloudCertificateName(name string) bool { + return name != "" && name != "." && name != ".." && filepath.Base(name) == name && + !strings.ContainsRune(name, 0) +} + +func (c *cloudInitializer) legacyCertificates(ctx context.Context) (map[string][]byte, error) { + body, err := c.requestCertificates(ctx, certificatePackagePath("cacertificates", "json")) + if err != nil { + return nil, fmt.Errorf("retrieve legacy Azure cloud certificates: %w", err) + } + var response struct { + Certificates []struct { + Name json.RawMessage `json:"Name"` + Body json.RawMessage `json:"CertBody"` + } `json:"Certificates"` + } + if err := json.Unmarshal(body, &response); err != nil { + return nil, fmt.Errorf("decode legacy Azure cloud certificates: %w", err) + } + if response.Certificates == nil { + return nil, errors.New("legacy Azure cloud response is missing a Certificates array") + } + certificates := make(map[string][]byte) + for _, cert := range response.Certificates { + var name string + if err := json.Unmarshal(cert.Name, &name); err != nil || !validCloudCertificateName(name) { + slog.Warn("rejecting invalid Azure cloud certificate filename") + continue + } + var certBody *string + if err := json.Unmarshal(cert.Body, &certBody); err != nil { + return nil, fmt.Errorf("decode legacy Azure cloud certificate body %s: %w", name, err) + } + if certBody == nil { + return nil, fmt.Errorf("legacy Azure cloud certificate %s is missing CertBody", name) + } + // Shell command substitution trims trailing LFs before CRLF normalization. + data := strings.ReplaceAll(strings.TrimRight(*certBody, "\n"), "\r\n", "\n") + "\n" + name = strings.ReplaceAll(name, ".cer", ".crt") + if err := c.writeFile("/root/AzureCACertificates/"+name, []byte(data)); err != nil { + return nil, fmt.Errorf("cache legacy Azure cloud certificate %s: %w", name, err) + } + certificates[name] = []byte(data) + } + return certificates, nil +} + +func (c *cloudInitializer) operationCertificates(ctx context.Context) (map[string][]byte, error) { + certificates := make(map[string][]byte) + for _, kind := range []string{"operationrequestsroot", "operationrequestsintermediate"} { + group, err := c.operationCertificateGroup(ctx, kind) + if err != nil { + return nil, err + } + maps.Copy(certificates, group) + } + return certificates, nil +} + +func (c *cloudInitializer) operationCertificateGroup(ctx context.Context, kind string) (map[string][]byte, error) { + body, err := c.requestCertificates(ctx, certificatePackagePath(kind, "json")) + if err != nil { + return nil, fmt.Errorf("retrieve Azure cloud %s: %w", kind, err) + } + var response struct { + Operations []struct { + // ResouceFileName is the spelling used by the WireServer protocol. + Name json.RawMessage `json:"ResouceFileName"` + } `json:"OperationsInfo"` + } + if err := json.Unmarshal(body, &response); err != nil { + return nil, fmt.Errorf("decode Azure cloud %s: %w", kind, err) + } + certificates := make(map[string][]byte) + found := false + for _, operation := range response.Operations { + var name string + if err := json.Unmarshal(operation.Name, &name); err != nil || name == "" { + slog.Warn("ignoring missing or non-string Azure cloud certificate filename") + continue + } + found = true + if !validCloudCertificateName(name) { + slog.Warn("rejecting invalid Azure cloud certificate filename") + continue + } + data, err := c.operationCertificate(ctx, name) + if err != nil { + if ctx.Err() != nil { + return nil, ctx.Err() + } + slog.Warn("could not retrieve Azure cloud certificate, continuing with remaining certificates", "name", name, "error", err) + continue + } + if err := c.writeFile("/root/AzureCACertificates/"+name, data); err != nil { + return nil, fmt.Errorf("cache Azure cloud certificate %s: %w", name, err) + } + certificates[name] = data + } + if !found { + return nil, fmt.Errorf("cloud %s contains no certificate filenames", kind) + } + return certificates, nil +} + +func (c *cloudInitializer) operationCertificate(ctx context.Context, filename string) ([]byte, error) { + name, extension := filename, filename + if suffix := filepath.Ext(filename); suffix != "" { + name = strings.TrimSuffix(filename, suffix) + extension = strings.TrimPrefix(suffix, ".") + } + body, err := c.requestCertificates(ctx, certificatePackagePath(name, extension)) + if err != nil { + return nil, fmt.Errorf("retrieve Azure cloud certificate %s: %w", filename, err) + } + body = bytes.TrimRight(body, "\n") + if len(body) == 0 { + return nil, fmt.Errorf("cloud certificate %s response is empty", filename) + } + return append(body, '\n'), nil +} diff --git a/aks-node-controller/cloud_certificate_transport_behavior_test.go b/aks-node-controller/cloud_certificate_transport_behavior_test.go new file mode 100644 index 00000000000..7145af50073 --- /dev/null +++ b/aks-node-controller/cloud_certificate_transport_behavior_test.go @@ -0,0 +1,121 @@ +package main + +import ( + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestCloudLegacyCertificateTransport(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + c.run = func(*exec.Cmd) error { + t.Fatal("certificate retrieval must not invoke trust-store tools") + return nil + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query() + if r.URL.Path != "/machine" || query.Get("comp") != "acmspackage" || + query.Get("type") != "cacertificates" || query.Get("ext") != "json" { + t.Errorf("unexpected legacy certificate request: %s", r.URL) + w.WriteHeader(http.StatusBadRequest) + return + } + _, _ = io.WriteString(w, `{"Certificates":[{"Name":"root.cer","CertBody":"first\r\nsecond\r\n"},{"Name":"../escape.cer","CertBody":"ignored"}]}`) + })) + defer server.Close() + c.wireEndpoint = server.URL + certificates, err := c.legacyCertificates(t.Context()) + require.NoError(t, err) + payload := []byte("first\nsecond\r\n") + require.Equal(t, map[string][]byte{"root.crt": payload}, certificates) + cached, err := os.ReadFile(c.path("/root/AzureCACertificates/root.crt")) + require.NoError(t, err) + require.Equal(t, payload, cached) + _, err = os.Stat(c.path("/root/escape.crt")) + require.ErrorIs(t, err, os.ErrNotExist) +} + +func TestCloudOperationCertificateTransport(t *testing.T) { + c := newTestCloudInitializer(t, "ID=azurelinux\n") + c.run = func(*exec.Cmd) error { + t.Fatal("certificate retrieval must not invoke trust-store tools") + return nil + } + serveCloudOperationTestResponses(t, c, + []string{"missing.crt", "empty.crt", "root+ca.crt", "unfiltered.cer"}, + []string{"intermediate.crt"}) + certificates, err := c.operationCertificates(t.Context()) + require.NoError(t, err) + payload := []byte("certificate payload\n") + require.Equal(t, map[string][]byte{ + "root+ca.crt": payload, + "unfiltered.cer": payload, + "intermediate.crt": payload, + }, certificates) + for name, want := range certificates { + cached, readErr := os.ReadFile(c.path("/root/AzureCACertificates/" + name)) + require.NoError(t, readErr) + require.Equal(t, want, cached) + } + _, err = os.Stat(c.path("/etc/pki/ca-trust/source/anchors")) + require.ErrorIs(t, err, os.ErrNotExist) +} + +func TestCloudCertificateTransportPreservesShellQuery(t *testing.T) { + for _, tc := range []struct { + name string + filename string + wantRequestURI string + }{ + { + name: "ordinary resource", + filename: "root.crt", + wantRequestURI: "/machine?comp=acmspackage&type=root&ext=crt", + }, + { + name: "literal plus", + filename: "root+ca.crt", + wantRequestURI: "/machine?comp=acmspackage&type=root+ca&ext=crt", + }, + { + name: "percent-escaped plus", + filename: "root%2Bca.crt", + wantRequestURI: "/machine?comp=acmspackage&type=root%2Bca&ext=crt", + }, + { + name: "ampersand", + filename: "root&ca.crt", + wantRequestURI: "/machine?comp=acmspackage&type=root&ca&ext=crt", + }, + { + name: "plus in extension", + filename: "root.crt+ca", + wantRequestURI: "/machine?comp=acmspackage&type=root&ext=crt+ca", + }, + { + name: "percent escape in extension", + filename: "root.c%2Brt", + wantRequestURI: "/machine?comp=acmspackage&type=root&ext=c%2Brt", + }, + } { + t.Run(tc.name, func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.RequestURI != tc.wantRequestURI { + t.Errorf("certificate request differs from init-aks-cloud.sh: got %q, want %q", r.RequestURI, tc.wantRequestURI) + } + _, _ = io.WriteString(w, "raw certificate payload\n\n") + })) + defer server.Close() + c.wireEndpoint = server.URL + payload, err := c.operationCertificate(t.Context(), tc.filename) + require.NoError(t, err) + require.Equal(t, "raw certificate payload\n", string(payload)) + }) + } +} diff --git a/aks-node-controller/cloud_certificate_transport_json_test.go b/aks-node-controller/cloud_certificate_transport_json_test.go new file mode 100644 index 00000000000..4396708e926 --- /dev/null +++ b/aks-node-controller/cloud_certificate_transport_json_test.go @@ -0,0 +1,174 @@ +package main + +import ( + "io" + "net/http" + "net/http/httptest" + "os" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestCloudOperationCertificateGroupJSON(t *testing.T) { + payloads := map[string][]byte{ + "root.crt": cloudTestCertificate(t), + "second.crt": cloudTestCertificate(t), + } + testCases := []struct { + name string + response string + wantNames []string + wantErr string + }{ + { + name: "one space after colon", + response: `{"OperationsInfo":[{"ResouceFileName": "root.crt"}]}`, + wantNames: []string{"root.crt"}, + }, + { + name: "compact JSON", + response: `{"OperationsInfo":[{"ResouceFileName":"root.crt"}]}`, + wantNames: []string{"root.crt"}, + }, + { + name: "indented JSON", + response: `{ + "OperationsInfo": [ + { + "ResouceFileName": "root.crt" + } + ] +}`, + wantNames: []string{"root.crt"}, + }, + { + name: "tabs CRLF and whitespace around colon", + response: "\r\n{\r\n\t\"OperationsInfo\"\t:\t[\r\n\t{\"ResouceFileName\"\r\n:\t \"root.crt\"}\r\n]\r\n}\t\r\n", + wantNames: []string{"root.crt"}, + }, + { + name: "JSON escaped filename", + response: `{"OperationsInfo":[{"ResouceFileName":"\u0072oot.crt"}]}`, + wantNames: []string{"root.crt"}, + }, + { + name: "ignore filenames at other levels", + response: `{ + "ResouceFileName": "wrong.crt", + "Metadata": {"ResouceFileName": "nested.crt"}, + "OperationsInfo": [ + {"ResouceFileName": "root.crt", "Metadata": {"ResouceFileName": "nested-entry.crt"}} + ] +}`, + wantNames: []string{"root.crt"}, + }, + { + name: "skip non-string and missing names", + response: `{"OperationsInfo":[ + {"ResouceFileName":42}, + {"ResouceFileName":null}, + {"OtherField":"ignored"}, + {"ResouceFileName":"root.crt"} +]}`, + wantNames: []string{"root.crt"}, + }, + { + name: "multiple resources", + response: `{"OperationsInfo":[{"ResouceFileName":"root.crt"},{"ResouceFileName":"second.crt"}]}`, + wantNames: []string{"root.crt", "second.crt"}, + }, + { + name: "truncated JSON containing a filename", + response: `{"OperationsInfo":[{"ResouceFileName": "root.crt"}]`, + wantErr: "decode Azure cloud", + }, + { + name: "filename only at the wrong level", + response: `{"ResouceFileName": "root.crt"}`, + wantErr: "contains no certificate filenames", + }, + { + name: "top-level array", + response: `[{"ResouceFileName": "root.crt"}]`, + wantErr: "decode Azure cloud", + }, + { + name: "OperationsInfo is not an array", + response: `{"OperationsInfo":{"ResouceFileName": "root.crt"}}`, + wantErr: "decode Azure cloud", + }, + { + name: "corrected spelling is not the protocol field", + response: `{"OperationsInfo":[{"ResourceFileName": "root.crt"}]}`, + wantErr: "contains no certificate filenames", + }, + { + name: "null OperationsInfo", + response: `{"OperationsInfo":null}`, + wantErr: "contains no certificate filenames", + }, + { + name: "empty OperationsInfo", + response: `{"OperationsInfo":[]}`, + wantErr: "contains no certificate filenames", + }, + { + name: "no string filenames", + response: `{"OperationsInfo":[{"ResouceFileName":42},{"ResouceFileName":null}]}`, + wantErr: "contains no certificate filenames", + }, + } + for _, kind := range []string{"operationrequestsroot", "operationrequestsintermediate"} { + for _, tc := range testCases { + t.Run(kind+"/"+tc.name, func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + manifestURI := "/machine?comp=acmspackage&type=" + kind + "&ext=json" + var manifests, downloads atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method + " " + r.RequestURI { + case http.MethodGet + " " + manifestURI: + manifests.Add(1) + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, tc.response) + case http.MethodGet + " /machine?comp=acmspackage&type=root&ext=crt": + downloads.Add(1) + _, _ = w.Write(payloads["root.crt"]) + case http.MethodGet + " /machine?comp=acmspackage&type=second&ext=crt": + downloads.Add(1) + _, _ = w.Write(payloads["second.crt"]) + default: + t.Errorf("unexpected certificate request: %s %s", r.Method, r.RequestURI) + w.WriteHeader(http.StatusNotFound) + } + })) + defer server.Close() + c.wireEndpoint = server.URL + + certificates, err := c.operationCertificateGroup(t.Context(), kind) + require.EqualValues(t, 1, manifests.Load()) + require.EqualValues(t, len(tc.wantNames), downloads.Load()) + if tc.wantErr != "" { + require.ErrorContains(t, err, tc.wantErr) + require.Nil(t, certificates) + _, statErr := os.Stat(c.path("/root/AzureCACertificates")) + require.ErrorIs(t, statErr, os.ErrNotExist) + return + } + require.NoError(t, err) + want := make(map[string][]byte, len(tc.wantNames)) + for _, name := range tc.wantNames { + want[name] = payloads[name] + cached, readErr := os.ReadFile(c.path("/root/AzureCACertificates/" + name)) + require.NoError(t, readErr) + require.Equal(t, payloads[name], cached) + } + require.Equal(t, want, certificates) + cached, readErr := os.ReadDir(c.path("/root/AzureCACertificates")) + require.NoError(t, readErr) + require.Len(t, cached, len(tc.wantNames)) + }) + } + } +} diff --git a/aks-node-controller/cloud_certificate_transport_test.go b/aks-node-controller/cloud_certificate_transport_test.go new file mode 100644 index 00000000000..5ca92e7db52 --- /dev/null +++ b/aks-node-controller/cloud_certificate_transport_test.go @@ -0,0 +1,246 @@ +package main + +import ( + "context" + "encoding/pem" + "io" + "net/http" + "net/http/httptest" + "os" + "strconv" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestCloudCertificateRequestRetryAndCancellation(t *testing.T) { + for _, tc := range []struct { + name string + status int + body string + failures int32 + wantWaits []time.Duration + }{ + {"transient", http.StatusServiceUnavailable, "do-not-log-body", 2, []time.Duration{3 * time.Second, 3 * time.Second}}, + {"rate limited", http.StatusForbidden, "RequestRateLimitExceeded", 2, []time.Duration{3 * time.Second, 6 * time.Second}}, + {"exhausted", http.StatusServiceUnavailable, "do-not-log-body", cloudRequestAttempts, nil}, + } { + t.Run(tc.name, func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + var attempts atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if attempts.Add(1) <= tc.failures { + w.WriteHeader(tc.status) + _, _ = io.WriteString(w, tc.body) + return + } + _, _ = io.WriteString(w, "success") + })) + defer server.Close() + c.wireEndpoint = server.URL + var waits []time.Duration + c.wait = func(_ context.Context, delay time.Duration) error { + waits = append(waits, delay) + return nil + } + body, err := c.requestCertificates(t.Context(), "/test") + if tc.failures == cloudRequestAttempts { + require.Error(t, err) + require.NotContains(t, err.Error(), tc.body) + require.EqualValues(t, cloudRequestAttempts, attempts.Load()) + require.Len(t, waits, cloudRequestAttempts-1) + } else { + require.NoError(t, err) + require.Equal(t, "success", string(body)) + require.Equal(t, tc.wantWaits, waits) + } + }) + } + t.Run("cancellation during backoff", func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + var attempts atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + attempts.Add(1) + w.WriteHeader(http.StatusServiceUnavailable) + })) + defer server.Close() + c.wireEndpoint = server.URL + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + c.wait = func(ctx context.Context, _ time.Duration) error { + cancel() + return ctx.Err() + } + _, err := c.requestCertificates(ctx, "/test") + require.ErrorIs(t, err, context.Canceled) + require.EqualValues(t, 1, attempts.Load()) + }) +} + +func TestCloudCertificateTruncatedHTTP200(t *testing.T) { + complete := cloudTestCertificate(t) + for _, tc := range []struct { + name string + failures int32 + }{ + {"recover on retry", 1}, + {"exhaust retries", cloudRequestAttempts}, + } { + t.Run(tc.name, func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + var attempts atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + attempt := attempts.Add(1) + w.Header().Set("Content-Length", strconv.Itoa(len(complete))) + w.WriteHeader(http.StatusOK) + if attempt <= tc.failures { + // Returning fewer bytes than Content-Length closes the response early. + _, _ = w.Write(complete[:len(complete)/2]) + return + } + _, _ = w.Write(complete) + })) + defer server.Close() + c.wireEndpoint = server.URL + waits := 0 + c.wait = func(ctx context.Context, _ time.Duration) error { + waits++ + return ctx.Err() + } + + body, err := c.requestCertificates(t.Context(), certificatePackagePath("root", "crt")) + wantAttempts := tc.failures + 1 + if tc.failures == cloudRequestAttempts { + wantAttempts = cloudRequestAttempts + require.ErrorIs(t, err, io.ErrUnexpectedEOF) + require.Nil(t, body) + } else { + require.NoError(t, err) + require.Equal(t, complete, body) + } + require.Equal(t, wantAttempts, attempts.Load()) + require.EqualValues(t, wantAttempts-1, waits) + }) + } +} + +func TestCloudOperationCertificateTruncatedDownload(t *testing.T) { + complete := cloudTestCertificate(t) + for _, failures := range []int32{1, cloudRequestAttempts} { + t.Run(strconv.Itoa(int(failures)), func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + var attempts atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.RequestURI { + case "/machine?comp=acmspackage&type=operationrequestsroot&ext=json": + _, _ = io.WriteString(w, `{"OperationsInfo":[{"ResouceFileName":"truncated.crt"},{"ResouceFileName":"complete.crt"}]}`) + case "/machine?comp=acmspackage&type=truncated&ext=crt": + attempt := attempts.Add(1) + w.Header().Set("Content-Length", strconv.Itoa(len(complete))) + w.WriteHeader(http.StatusOK) + if attempt <= failures { + _, _ = w.Write(complete[:len(complete)/2]) + return + } + _, _ = w.Write(complete) + case "/machine?comp=acmspackage&type=complete&ext=crt": + _, _ = w.Write(complete) + default: + t.Errorf("unexpected certificate request: %s", r.RequestURI) + w.WriteHeader(http.StatusNotFound) + } + })) + defer server.Close() + c.wireEndpoint = server.URL + + certificates, err := c.operationCertificateGroup(t.Context(), "operationrequestsroot") + require.NoError(t, err) + want := map[string][]byte{"complete.crt": complete} + wantAttempts := failures + 1 + if failures == cloudRequestAttempts { + wantAttempts = cloudRequestAttempts + _, statErr := os.Stat(c.path("/root/AzureCACertificates/truncated.crt")) + require.ErrorIs(t, statErr, os.ErrNotExist) + } else { + want["truncated.crt"] = complete + } + require.Equal(t, wantAttempts, attempts.Load()) + require.Equal(t, want, certificates) + for name, payload := range want { + cached, readErr := os.ReadFile(c.path("/root/AzureCACertificates/" + name)) + require.NoError(t, readErr) + require.Equal(t, payload, cached) + } + }) + } +} + +func TestCloudCertificateCloseDelimitedResponse(t *testing.T) { + complete := cloudTestCertificate(t) + partial := complete[:len(complete)/2] + c := newTestCloudInitializer(t, cloudTestUbuntu) + var attempts atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + attempts.Add(1) + hijacker, ok := w.(http.Hijacker) + if !ok { + t.Error("test server does not support connection hijacking") + return + } + conn, writer, err := hijacker.Hijack() + if err != nil { + t.Errorf("hijack test connection: %v", err) + return + } + defer conn.Close() + if _, err := writer.WriteString("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n" + string(partial)); err != nil { + t.Errorf("write close-delimited response: %v", err) + return + } + if err := writer.Flush(); err != nil { + t.Errorf("flush close-delimited response: %v", err) + } + })) + defer server.Close() + c.wireEndpoint = server.URL + + body, err := c.requestCertificates(t.Context(), certificatePackagePath("root", "crt")) + require.NoError(t, err) + require.Equal(t, partial, body) + require.EqualValues(t, 1, attempts.Load()) +} + +func TestCloudCertificateRequestsDoNotFollowRedirects(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + var redirected atomic.Int32 + target := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { redirected.Add(1) })) + defer target.Close() + source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, target.URL, http.StatusFound) + })) + defer source.Close() + c.wireEndpoint = source.URL + _, err := c.requestCertificates(t.Context(), "/test") + require.ErrorContains(t, err, "HTTP 302") + require.Zero(t, redirected.Load()) +} + +func TestCloudCertificateNamesAndPublicContent(t *testing.T) { + for _, name := range []string{"", ".", "..", "../root.crt", "/root.crt", "root\x00.crt"} { + require.False(t, validCloudCertificateName(name), name) + } + for _, name := range []string{"root+ca.crt", `..\root.crt`, "root\n.crt"} { + require.True(t, validCloudCertificateName(name), name) + } + cert := cloudTestCertificate(t) + private := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: []byte("not-a-real-private-key")}) + got, err := publicCloudCertificates(append(private, cert...)) + require.NoError(t, err) + require.Equal(t, cert, got) + for _, bad := range [][]byte{nil, private, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: []byte("invalid")})} { + _, err = publicCloudCertificates(bad) + require.Error(t, err) + } +} diff --git a/aks-node-controller/cloud_certificates.go b/aks-node-controller/cloud_certificates.go new file mode 100644 index 00000000000..dfeace8b4c6 --- /dev/null +++ b/aks-node-controller/cloud_certificates.go @@ -0,0 +1,69 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "strings" +) + +func (c *cloudInitializer) refresh(ctx context.Context, platform cloudPlatform, location string) (bool, error) { + location, err := normalizeCloudLocation(location) + if err != nil { + return false, err + } + c.clearCertificateCache() + legacy := strings.HasPrefix(location, "ussec") || strings.HasPrefix(location, "usnat") + slog.Info("selecting Azure cloud certificate endpoint", "legacy", legacy, "location", location) + if !legacy { + optedIn, optInErr := c.isOptedInForRootCerts(ctx) + if optInErr != nil || !optedIn { + return false, optInErr + } + } + var certificates map[string][]byte + if legacy { + certificates, err = c.legacyCertificates(ctx) + } else { + certificates, err = c.operationCertificates(ctx) + } + if err != nil { + return false, err + } + if err := c.installCertificates(ctx, platform, certificates); err != nil { + if ctx.Err() != nil { + return false, ctx.Err() + } + if legacy { + slog.Warn("legacy Azure cloud CA certificate installation failed, continuing cloud initialization", "error", err) + return true, nil + } + return false, fmt.Errorf("install Azure cloud CA certificates: %w", err) + } + slog.Info("installed Azure cloud CA certificates") + return true, nil +} + +// isOptedInForRootCerts accepts only a JSON boolean true; other decodable responses skip installation. +func (c *cloudInitializer) isOptedInForRootCerts(ctx context.Context) (bool, error) { + body, err := c.requestCertificates(ctx, "/acms/isOptedInForRootCerts") + if err != nil { + return false, fmt.Errorf("check Azure cloud root certificate opt-in: %w", err) + } + if len(bytes.TrimRight(body, "\n")) == 0 { + return false, errors.New("cloud root certificate opt-in response is empty") + } + var response map[string]json.RawMessage + if err := json.Unmarshal(body, &response); err != nil { + slog.Warn("could not decode Azure cloud root certificate opt-in, skipping certificate installation", "error", err) + return false, nil + } + if !bytes.Equal(bytes.TrimSpace(response["IsOptedInForRootCerts"]), []byte("true")) { + slog.Info("Azure cloud root certificates are not opted in, skipping certificate installation") + return false, nil + } + return true, nil +} diff --git a/aks-node-controller/cloud_certificates_test.go b/aks-node-controller/cloud_certificates_test.go new file mode 100644 index 00000000000..daebb600aa2 --- /dev/null +++ b/aks-node-controller/cloud_certificates_test.go @@ -0,0 +1,443 @@ +package main + +import ( + "context" + "encoding/pem" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestCloudCertificateRefreshModes(t *testing.T) { + cert := cloudTestCertificate(t) + for _, platform := range []struct{ name, release, directory, filename, command string }{ + {"Ubuntu", cloudTestUbuntu, "/usr/local/share/ca-certificates", "root.crt", "update-ca-certificates"}, + {"AzureLinux", "ID=azurelinux\n", "/etc/pki/ca-trust/source/anchors", "root.crt", "update-ca-trust"}, + {"Flatcar", "ID=flatcar\n", "/etc/ssl/certs", "root.pem", "update-ca-certificates"}, + {"ACL", "ID=azurecontainerlinux\n", "/etc/pki/ca-trust/source/anchors", "root.crt", "update-ca-trust"}, + } { + for _, mode := range []struct{ name, location, optIn string }{ + {"opt-out", "westus2", `{"IsOptedInForRootCerts":false}`}, + {"rcv1p", "westus2", `{"IsOptedInForRootCerts":true}`}, + {"legacy", " US NAT East ", "not used"}, + } { + t.Run(platform.name+"/"+mode.name, func(t *testing.T) { + c := newTestCloudInitializer(t, platform.release) + serveCloudTestResponses(t, c, cert, mode.optIn) + var commands []string + c.run = func(cmd *exec.Cmd) error { + commands = append(commands, cmd.Args[0]) + return nil + } + require.NoError(t, c.refreshCertificates(t.Context(), mode.location)) + if mode.name == "opt-out" { + require.Empty(t, commands) + return + } + require.Equal(t, []string{platform.command}, commands) + installed, err := os.ReadFile(c.path(filepath.Join(platform.directory, platform.filename))) + require.NoError(t, err) + expected := cert + if mode.name == "legacy" { + expected = []byte(strings.TrimSuffix(string(cert), "\n") + "\r\n") + } + require.Equal(t, expected, installed) + }) + } + } +} + +func TestCloudCertificateRefreshNormalizesLocation(t *testing.T) { + cert := cloudTestCertificate(t) + for _, tc := range []struct { + name, location string + legacy bool + }{ + {"ussec lowercase", "ussecgov", true}, + {"ussec mixed case", "usSecGov", true}, + {"ussec whitespace", " \tUS SEC GOV\r\n", true}, + {"usnat lowercase", "usnateast", true}, + {"usnat mixed case", "usNatEast", true}, + {"usnat whitespace", " US NAT East ", true}, + {"rcv1p lowercase", "westus2", false}, + {"rcv1p mixed case and whitespace", " \tWest US2\n", false}, + {"rcv1p empty", "", false}, + {"rcv1p whitespace only", " \t\n", false}, + } { + t.Run(tc.name, func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + requests := serveCloudTestResponses(t, c, cert, `{"IsOptedInForRootCerts":true}`) + var commands []string + c.run = func(cmd *exec.Cmd) error { + commands = append(commands, cmd.Args[0]) + return nil + } + platform, err := c.platform() + require.NoError(t, err) + refreshed, err := c.refresh(t.Context(), platform, tc.location) + require.NoError(t, err) + require.True(t, refreshed) + require.Equal(t, []string{"update-ca-certificates"}, commands) + wantRequests := 5 + wantFirst := "/acms/isOptedInForRootCerts?" + if tc.legacy { + wantRequests = 1 + wantFirst = "/machine?comp=acmspackage&type=cacertificates&ext=json" + } + require.Len(t, requests, wantRequests) + require.Equal(t, wantFirst, <-requests) + }) + } +} + +func TestCloudCertificateRefreshRejectsInvalidLocationBeforeSideEffects(t *testing.T) { + for _, location := range []string{`westus";echo bad`, "westus%bad", "ussec/gov"} { + t.Run(location, func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + requests := serveCloudTestResponses(t, c, nil, `{"IsOptedInForRootCerts":false}`) + c.run = func(*exec.Cmd) error { + t.Fatal("invalid locations must not update the trust store") + return nil + } + require.NoError(t, c.writeFile("/root/AzureCACertificates/stale.crt", []byte("keep"))) + platform, err := c.platform() + require.NoError(t, err) + refreshed, err := c.refresh(t.Context(), platform, location) + require.ErrorContains(t, err, "cloud location contains unsupported characters") + require.False(t, refreshed) + require.Empty(t, requests) + cached, err := os.ReadFile(c.path("/root/AzureCACertificates/stale.crt")) + require.NoError(t, err) + require.Equal(t, "keep", string(cached)) + }) + } +} + +func TestCloudRootCertificateOptIn(t *testing.T) { + for _, tc := range []struct { + name, response string + wantOptedIn bool + wantError string + }{ + {"opted in", `{"IsOptedInForRootCerts":true}`, true, ""}, + {"opted out", `{"IsOptedInForRootCerts":false}`, false, ""}, + {"malformed JSON", "not json", false, ""}, + {"missing field", `{}`, false, ""}, + {"wrong field case", `{"isOptedInForRootCerts":true}`, false, ""}, + {"string true", `{"IsOptedInForRootCerts":"true"}`, false, ""}, + {"whitespace only", " ", false, ""}, + {"empty response", "", false, "response is empty"}, + {"newlines only", "\n\n", false, "response is empty"}, + } { + t.Run(tc.name, func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + requests := serveCloudTestResponses(t, c, nil, tc.response) + c.run = func(*exec.Cmd) error { + t.Fatal("opt-in checks must not update the trust store") + return nil + } + require.NoError(t, c.writeFile("/root/AzureCACertificates/stale.crt", []byte("keep"))) + optedIn, err := c.isOptedInForRootCerts(t.Context()) + if tc.wantError != "" { + require.ErrorContains(t, err, tc.wantError) + } else { + require.NoError(t, err) + } + require.Equal(t, tc.wantOptedIn, optedIn) + require.Len(t, requests, 1) + require.Equal(t, "/acms/isOptedInForRootCerts?", <-requests) + cached, err := os.ReadFile(c.path("/root/AzureCACertificates/stale.crt")) + require.NoError(t, err) + require.Equal(t, "keep", string(cached)) + }) + } +} + +func TestCloudRootCertificateOptInRequestErrors(t *testing.T) { + for _, tc := range []struct { + name string + canceled bool + }{ + {"HTTP failure", false}, + {"cancellation", true}, + } { + t.Run(tc.name, func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + var requests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + requests.Add(1) + http.Error(w, "unavailable", http.StatusServiceUnavailable) + })) + t.Cleanup(server.Close) + c.wireEndpoint = server.URL + c.wireClient = server.Client() + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + if tc.canceled { + cancel() + } + optedIn, err := c.isOptedInForRootCerts(ctx) + require.False(t, optedIn) + require.ErrorContains(t, err, "check Azure cloud root certificate opt-in") + if tc.canceled { + require.ErrorIs(t, err, context.Canceled) + require.Zero(t, requests.Load()) + } else { + require.Positive(t, requests.Load()) + } + }) + } +} + +func TestCloudCertificateRefreshNonTrueOptInResponsesSkip(t *testing.T) { + for _, response := range []string{ + "not json", " ", `{}`, `null`, `[]`, `{"IsOptedInForRootCerts":false}`, + `{"IsOptedInForRootCerts":null}`, `{"IsOptedInForRootCerts":"false"}`, + `{"IsOptedInForRootCerts":"true"}`, `{"IsOptedInForRootCerts":1}`, + `{"isOptedInForRootCerts":true}`, + } { + t.Run(response, func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + requests := serveCloudTestResponses(t, c, nil, response) + c.run = func(*exec.Cmd) error { + t.Fatal("non-true opt-in must not update the trust store") + return nil + } + require.NoError(t, c.refreshCertificates(t.Context(), "westus2")) + require.Len(t, requests, 1) + }) + } +} + +func TestCloudLegacyCertificateRefreshTrustFailureIsBestEffort(t *testing.T) { + c := newTestCloudInitializer(t, "ID=azurelinux\n") + serveCloudTestResponses(t, c, cloudTestCertificate(t), "not used") + c.run = func(cmd *exec.Cmd) error { + require.Equal(t, "update-ca-trust", cmd.Args[0]) + return errors.New("trust store update failed") + } + require.NoError(t, c.refreshCertificates(t.Context(), "usnateast")) +} + +func TestCloudCertificateOptInEmptyResponsesFail(t *testing.T) { + for _, response := range []string{"", "\n", "\n\n"} { + t.Run(fmt.Sprintf("%q", response), func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + serveCloudTestResponses(t, c, nil, response) + require.ErrorContains(t, c.refreshCertificates(t.Context(), "westus2"), "response is empty") + }) + } +} + +func TestCloudCertificateRefreshClearsCachedFiles(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + serveCloudTestResponses(t, c, nil, `{"IsOptedInForRootCerts":false}`) + for _, name := range []string{"stale.crt", ".stale.crt", "certificate-without-extension"} { + require.NoError(t, c.writeFile("/root/AzureCACertificates/"+name, []byte("stale"))) + } + require.NoError(t, c.writeFile("/usr/local/share/ca-certificates/existing.crt", []byte("keep"))) + require.NoError(t, c.refreshCertificates(t.Context(), "westus2")) + entries, err := os.ReadDir(c.path("/root/AzureCACertificates")) + require.NoError(t, err) + require.Empty(t, entries) + data, err := os.ReadFile(c.path("/usr/local/share/ca-certificates/existing.crt")) + require.NoError(t, err) + require.Equal(t, "keep", string(data)) +} + +func TestCloudCertificatePayloadsArePassedToTrustStoreTools(t *testing.T) { + for _, tc := range []struct{ name, location, want string }{ + {"legacy", "usnateast", "not a PEM certificate\r\n"}, + {"rcv1p", "westus2", "not a PEM certificate\n"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("AKS_CLOUD_LOG_CERTIFICATES", "true") + logs := installLogCapturer(t) + c := newTestCloudInitializer(t, cloudTestUbuntu) + serveCloudTestResponses(t, c, []byte("not a PEM certificate\n"), `{"IsOptedInForRootCerts":true}`) + var commands []string + c.run = func(cmd *exec.Cmd) error { + commands = append(commands, cmd.Args[0]) + return nil + } + require.NoError(t, c.refreshCertificates(t.Context(), tc.location)) + got, err := os.ReadFile(c.path("/usr/local/share/ca-certificates/root.crt")) + require.NoError(t, err) + require.Equal(t, tc.want, string(got)) + require.Equal(t, []string{"update-ca-certificates"}, commands) + for _, record := range logs.getRecords() { + for _, value := range record.Attrs { + require.NotContains(t, value, "not a PEM certificate") + } + } + }) + } +} + +func TestCloudCertificateOperationDownloadFailures(t *testing.T) { + for _, tc := range []struct { + name string + roots []string + intermediates []string + wantInstalled []string + wantError bool + }{ + {"partial group", []string{"missing.crt", "root.crt"}, []string{"intermediate.crt"}, []string{"root.crt", "intermediate.crt"}, false}, + {"empty root group after failures", []string{"missing.crt"}, []string{"intermediate.crt"}, []string{"intermediate.crt"}, false}, + {"empty certificate response", []string{"empty.crt"}, []string{"intermediate.crt"}, []string{"intermediate.crt"}, false}, + {"non-crt root", []string{"root.cer"}, []string{"intermediate.crt"}, []string{"intermediate.crt"}, false}, + {"all downloads fail", []string{"missing.crt"}, []string{"missing.crt"}, nil, true}, + {"no crt files", []string{"root.cer"}, []string{"intermediate.cer"}, nil, true}, + } { + t.Run(tc.name, func(t *testing.T) { + c := newTestCloudInitializer(t, "ID=azurelinux\n") + serveCloudOperationTestResponses(t, c, tc.roots, tc.intermediates) + var commands []string + c.run = func(cmd *exec.Cmd) error { + commands = append(commands, cmd.Args[0]) + return nil + } + err := c.refreshCertificates(t.Context(), "westus2") + if tc.wantError { + require.ErrorContains(t, err, "no *.crt files") + require.Empty(t, commands) + return + } + require.NoError(t, err) + require.Equal(t, []string{"update-ca-trust"}, commands) + for _, name := range tc.wantInstalled { + data, readErr := os.ReadFile(c.path("/etc/pki/ca-trust/source/anchors/" + name)) + require.NoError(t, readErr) + require.Equal(t, "certificate payload\n", string(data)) + } + for _, name := range []string{"missing.crt", "empty.crt", "root.cer"} { + _, err = os.Stat(c.path("/etc/pki/ca-trust/source/anchors/" + name)) + require.ErrorIs(t, err, os.ErrNotExist) + } + }) + } +} + +func TestCloudLegacyCertificateInstallationDoesNotIgnoreCancellation(t *testing.T) { + c := newTestCloudInitializer(t, "ID=azurelinux\n") + serveCloudTestResponses(t, c, cloudTestCertificate(t), "not used") + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + c.run = func(*exec.Cmd) error { + cancel() + return ctx.Err() + } + require.ErrorIs(t, c.refreshCertificates(ctx, "usnateast"), context.Canceled) +} + +func TestCloudCertificateResourceNamesPreserveShellQuery(t *testing.T) { + c := newTestCloudInitializer(t, "ID=azurelinux\n") + cert := cloudTestCertificate(t) + var fetched atomic.Bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch kind := r.URL.Query().Get("type"); { + case r.URL.Path == "/acms/isOptedInForRootCerts": + _, _ = io.WriteString(w, `{"IsOptedInForRootCerts":true}`) + case kind == "operationrequestsroot": + _, _ = io.WriteString(w, `{"OperationsInfo":[{"ResouceFileName":"root+ca.crt"}]}`) + case kind == "operationrequestsintermediate": + _, _ = io.WriteString(w, `{"OperationsInfo":[{"ResouceFileName":"intermediate.crt"}]}`) + case r.RequestURI == "/machine?comp=acmspackage&type=root+ca&ext=crt", kind == "intermediate": + fetched.Store(true) + _, _ = w.Write(cert) + default: + t.Errorf("unexpected certificate resource: %s", r.RequestURI) + w.WriteHeader(http.StatusBadRequest) + } + })) + defer server.Close() + c.wireEndpoint = server.URL + require.NoError(t, c.refreshCertificates(t.Context(), "westus2")) + require.True(t, fetched.Load()) + installed, err := os.ReadFile(c.path("/etc/pki/ca-trust/source/anchors/root+ca.crt")) + require.NoError(t, err) + require.Equal(t, cert, installed) +} + +func TestCloudCertificateLoggingIsOptInAndPublicOnly(t *testing.T) { + for _, enabled := range []string{"false", "true"} { + t.Run(enabled, func(t *testing.T) { + t.Setenv("AKS_CLOUD_LOG_CERTIFICATES", enabled) + logs := installLogCapturer(t) + c := newTestCloudInitializer(t, "ID=azurelinux\n") + cert := cloudTestCertificate(t) + payload := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: []byte("not-a-real-private-key")}) + payload = append(payload, cert...) + serveCloudTestResponses(t, c, payload, `{"IsOptedInForRootCerts":true}`) + require.NoError(t, c.refreshCertificates(t.Context(), "westus2")) + found := false + for _, record := range logs.getRecords() { + for _, value := range record.Attrs { + require.NotContains(t, value, "PRIVATE KEY") + if strings.Contains(value, "BEGIN CERTIFICATE") { + found = true + } + } + } + require.Equal(t, enabled == "true", found) + got, err := os.ReadFile(c.path("/etc/pki/ca-trust/source/anchors/root.crt")) + require.NoError(t, err) + require.Equal(t, payload, got) + }) + } +} + +func TestCloudCertificateInvalidOperationsDoNotInstall(t *testing.T) { + for _, response := range []string{ + `{}`, `{"OperationsInfo":[]}`, `{"OperationsInfo":[{"ResouceFileName":"../escape.crt"}]}`, + `{"OperationsInfo":[{"ResouceFileName":"/escape.crt"}]}`, `{"OperationsInfo":[{"ResouceFileName":"missing-extension"}]}`, + } { + t.Run(response, func(t *testing.T) { + c := newTestCloudInitializer(t, "ID=azurelinux\n") + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/acms/isOptedInForRootCerts" { + _, _ = io.WriteString(w, `{"IsOptedInForRootCerts":true}`) + } else { + _, _ = io.WriteString(w, response) + } + })) + defer server.Close() + c.wireEndpoint = server.URL + c.run = func(*exec.Cmd) error { + t.Fatal("invalid operations must not install certificates") + return nil + } + require.Error(t, c.refreshCertificates(t.Context(), "westus2")) + _, err := os.Stat(c.path("/etc/pki/ca-trust/source/anchors")) + require.ErrorIs(t, err, os.ErrNotExist) + }) + } +} + +func TestCloudPeriodicRefreshDoesNotInitializeRepositoriesOrSchedules(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + requests := serveCloudTestResponses(t, c, cloudTestCertificate(t), `{"IsOptedInForRootCerts":true}`) + var commands []string + c.run = func(cmd *exec.Cmd) error { + commands = append(commands, strings.Join(cmd.Args, " ")) + return nil + } + require.NoError(t, c.refreshCertificates(t.Context(), "westus2")) + require.Equal(t, []string{"update-ca-certificates"}, commands) + require.Len(t, requests, 5) + _, err := os.Stat(c.path(defaultAptSourcesDir)) + require.ErrorIs(t, err, os.ErrNotExist) + events := c.eventLogger.Events() + require.Len(t, events, 1) + require.Equal(t, "AKS.AKSNodeController.CloudCertificateRefresh", events[0].TaskName) +} diff --git a/aks-node-controller/cloud_init.go b/aks-node-controller/cloud_init.go index 42d39fb3af7..58375af0c3e 100644 --- a/aks-node-controller/cloud_init.go +++ b/aks-node-controller/cloud_init.go @@ -2,12 +2,14 @@ package main import ( "context" + "errors" "fmt" "log/slog" "os" "os/exec" "path/filepath" "strings" + "time" "github.com/Azure/agentbaker/aks-node-controller/parser" "github.com/Azure/agentbaker/aks-node-controller/pkg/nodeconfigutils" @@ -20,24 +22,35 @@ const ( nbcCloudInitGuard = `if [ -f "${INIT_AKS_CLOUD_FILEPATH}" ] && [ ! -f "/run/aks/init-aks-cloud.done" ]; then` ) -func cloudInitializationSettings(flags ProvisionFlags) (string, string, bool, error) { - if flags.NBCCmd != "" { - return nbcCloudInitializationSettings(flags.NBCCmd) +type cloudInitConfig struct { + Location string + RepoDepotEndpoint string + Timeout time.Duration +} + +func newCloudInitConfig(location, repoDepotEndpoint, cseTimeout string) (cloudInitConfig, error) { + timeout, err := time.ParseDuration(cseTimeout + "s") + if err != nil || timeout <= 0 { + return cloudInitConfig{}, fmt.Errorf("invalid cloud initialization timeout %q", cseTimeout) } + return cloudInitConfig{Location: location, RepoDepotEndpoint: repoDepotEndpoint, Timeout: timeout}, nil +} - if flags.ProvisionConfig == "" { - return "", "", false, fmt.Errorf("--provision-config or --nbc-cmd is required") +// nativeCloudInitConfig reads the settings that the CSE command would use from AKSNodeConfig. +func nativeCloudInitConfig(path string) (cloudInitConfig, error) { + if path == "" { + return cloudInitConfig{}, errors.New("--provision-config or --nbc-cmd is required") } - content, err := os.ReadFile(flags.ProvisionConfig) + content, err := os.ReadFile(path) if err != nil { - return "", "", false, fmt.Errorf("read provision config: %w", err) + return cloudInitConfig{}, fmt.Errorf("read provision config: %w", err) } config, err := nodeconfigutils.UnmarshalConfigurationV1(content) if err != nil { - return "", "", false, fmt.Errorf("decode provision config: %w", err) + return cloudInitConfig{}, fmt.Errorf("decode provision config: %w", err) } location, endpoint := parser.CloudInitializationSettings(config) - return location, endpoint, true, nil + return newCloudInitConfig(location, endpoint, parser.GetCSETimeout(int(config.GetCseTimeout()))) } func nbcCloudInitializationSettings(path string) (string, string, bool, error) { @@ -64,8 +77,24 @@ func nbcCloudInitializationSettings(path string) (string, string, bool, error) { return location, endpoint, true, nil } +// initializeCloud runs before hotfix acquisition so that custom clouds can reach RepoDepot. +// AKSNodeConfig provisioning initializes natively; NBC provisioning keeps the shell initializer. +// The marker makes the provisioning CSE command skip init-aks-cloud.sh. Without it, for example +// after a failure, provisioning runs the VHD's init-aks-cloud.sh as it did before this handoff. func (a *App) initializeCloud(ctx context.Context, flags ProvisionFlags, scriptPath, markerPath string) error { - location, endpoint, supported, err := cloudInitializationSettings(flags) + if flags.NBCCmd == "" { + config, err := nativeCloudInitConfig(flags.ProvisionConfig) + if err != nil { + return err + } + if err := a.runNativeCloudInitialization(ctx, config); err != nil { + return err + } + writeCloudInitMarker(markerPath) + return nil + } + + location, endpoint, supported, err := nbcCloudInitializationSettings(flags.NBCCmd) if err != nil { return err } @@ -82,10 +111,62 @@ func (a *App) initializeCloud(ctx context.Context, flags ProvisionFlags, scriptP if err := a.cmdRun(cmd); err != nil { return fmt.Errorf("initialize cloud: %w", err) } - if err := os.MkdirAll(filepath.Dir(markerPath), 0755); err != nil { + writeCloudInitMarker(markerPath) + return nil +} + +func (a *App) runNativeCloudInitialization(ctx context.Context, config cloudInitConfig) error { + if a.initializeNativeCloud != nil { + return a.initializeNativeCloud(ctx, config) + } + initializer := newCloudInitializer(a) + defer initializer.close() + return initializer.initialize(ctx, config) +} + +func writeCloudInitMarker(path string) { + if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { slog.Warn("failed to create cloud initialization marker; provisioning will initialize again", "error", err) - } else if err := os.WriteFile(markerPath, nil, 0600); err != nil { + } else if err := os.WriteFile(path, nil, 0600); err != nil { slog.Warn("failed to create cloud initialization marker; provisioning will initialize again", "error", err) } - return nil +} + +func (c *cloudInitializer) initialize(ctx context.Context, config cloudInitConfig) error { + initCtx, cancel := context.WithTimeout(ctx, config.Timeout) + defer cancel() + return c.withEvent("CloudInitialization", func() error { + location, err := normalizeCloudLocation(config.Location) + if err != nil { + return err + } + platform, err := c.platform() + if err != nil { + return err + } + eligible, err := c.refresh(initCtx, platform, location) + if err != nil { + return err + } + // Like init-aks-cloud.sh, configure repositories before scheduling certificate refresh. + repositoryErr := c.withEvent("CloudRepositoryInitialization", func() error { + return c.initializeRepositories(initCtx, platform, config.RepoDepotEndpoint) + }) + if errors.Is(repositoryErr, errCloudRepositoryCacheRefresh) { + if contextErr := initCtx.Err(); contextErr != nil { + return contextErr + } + // The shell reports cache-refresh failures without propagating them to CSE. + slog.Warn("RepoDepot package cache refresh failed, continuing cloud initialization", "error", repositoryErr) + } else if repositoryErr != nil { + return repositoryErr + } + if !eligible { + return nil + } + if err := c.installRefreshSchedule(initCtx, platform, location); err != nil { + return fmt.Errorf("schedule Azure cloud certificate refresh: %w", err) + } + return nil + }) } diff --git a/aks-node-controller/cloud_init_test.go b/aks-node-controller/cloud_init_test.go index dc0200e0468..704c405f9e7 100644 --- a/aks-node-controller/cloud_init_test.go +++ b/aks-node-controller/cloud_init_test.go @@ -3,138 +3,172 @@ package main import ( "context" "errors" + "io" + "net/http" + "net/http/httptest" "os" "os/exec" "path/filepath" "runtime" + "slices" + "strings" "testing" + "time" + "github.com/Azure/agentbaker/aks-node-controller/config" + "github.com/Azure/agentbaker/aks-node-controller/helpers" "github.com/stretchr/testify/require" ) -func TestCloudInitializationSettings(t *testing.T) { +func TestNBCCloudInitializationSettings(t *testing.T) { dir := t.TempDir() - configPath := filepath.Join(dir, "config.json") nbcPath := filepath.Join(dir, "nbc.sh") - require.NoError(t, os.WriteFile(configPath, []byte(`{ - "cluster_config":{"location":"config-region"}, - "custom_cloud_config":{"custom_cloud_env_name":"AKSCustom","repo_depot_endpoint":"https://config"} - }`), 0600)) - t.Run("NBC takes precedence and preserves shell-quoted values", func(t *testing.T) { + t.Run("preserves shell-quoted values", func(t *testing.T) { nbc := nbcCloudInitGuard + ` REPO_DEPOT_ENDPOINT='https://nbc/'"'"'$(touch nope)' LOCATION='usnat test' "${INIT_AKS_CLOUD_FILEPATH}"; fi; LOCATION='usnat test' /usr/bin/nohup /bin/bash ` require.NoError(t, os.WriteFile(nbcPath, []byte(nbc), 0600)) - location, endpoint, supported, err := cloudInitializationSettings(ProvisionFlags{ProvisionConfig: configPath, NBCCmd: nbcPath}) + location, endpoint, supported, err := nbcCloudInitializationSettings(nbcPath) require.NoError(t, err) require.True(t, supported) require.Equal(t, "usnat test", location) require.Equal(t, "https://nbc/'$(touch nope)", endpoint) }) - t.Run("older NBC retains old ordering even when config is present", func(t *testing.T) { + t.Run("older NBC retains old ordering", func(t *testing.T) { require.NoError(t, os.WriteFile(nbcPath, []byte(`REPO_DEPOT_ENDPOINT="https://old" LOCATION=old "${INIT_AKS_CLOUD_FILEPATH}";`), 0600)) - _, _, supported, err := cloudInitializationSettings(ProvisionFlags{ProvisionConfig: configPath, NBCCmd: nbcPath}) + _, _, supported, err := nbcCloudInitializationSettings(nbcPath) require.NoError(t, err) require.False(t, supported) }) - t.Run("config-only custom cloud", func(t *testing.T) { - location, endpoint, supported, err := cloudInitializationSettings(ProvisionFlags{ProvisionConfig: configPath}) - require.NoError(t, err) - require.True(t, supported) - require.Equal(t, "config-region", location) - require.Equal(t, "https://config", endpoint) - }) - t.Run("non-custom cloud ignores endpoint", func(t *testing.T) { - path := filepath.Join(dir, "public.json") - require.NoError(t, os.WriteFile(path, []byte(`{ - "clusterConfig":{"location":"eastus"}, - "customCloudConfig":{"customCloudEnvName":"public","repoDepotEndpoint":"https://ignored"} - }`), 0600)) - location, endpoint, supported, err := cloudInitializationSettings(ProvisionFlags{ProvisionConfig: path}) - require.NoError(t, err) - require.True(t, supported) - require.Equal(t, "eastus", location) - require.Empty(t, endpoint) - }) t.Run("empty settings are passed through", func(t *testing.T) { require.NoError(t, os.WriteFile(nbcPath, []byte(nbcCloudInitGuard+` REPO_DEPOT_ENDPOINT='' LOCATION='' "${INIT_AKS_CLOUD_FILEPATH}"; fi; LOCATION=''`), 0600)) - location, endpoint, supported, err := cloudInitializationSettings(ProvisionFlags{NBCCmd: nbcPath}) + location, endpoint, supported, err := nbcCloudInitializationSettings(nbcPath) require.NoError(t, err) require.True(t, supported) require.Empty(t, location) require.Empty(t, endpoint) }) - t.Run("missing settings fail instead of using config", func(t *testing.T) { + t.Run("missing settings fail", func(t *testing.T) { require.NoError(t, os.WriteFile(nbcPath, []byte(nbcCloudInitGuard+` LOCATION='usnat'`), 0600)) - _, _, _, err := cloudInitializationSettings(ProvisionFlags{ProvisionConfig: configPath, NBCCmd: nbcPath}) + _, _, _, err := nbcCloudInitializationSettings(nbcPath) require.ErrorContains(t, err, "missing cloud initialization settings") }) + t.Run("directory fails", func(t *testing.T) { + _, _, _, err := nbcCloudInitializationSettings(dir) + require.ErrorContains(t, err, "regular file") + }) +} + +func TestNativeCloudInitConfig(t *testing.T) { + dir := t.TempDir() + write := func(name, content string) string { + path := filepath.Join(dir, name) + require.NoError(t, os.WriteFile(path, []byte(content), 0600)) + return path + } + + t.Run("custom cloud", func(t *testing.T) { + config, err := nativeCloudInitConfig(write("custom.json", `{ + "cluster_config":{"location":"config-region"}, + "custom_cloud_config":{"custom_cloud_env_name":"AKSCustom","repo_depot_endpoint":"https://config"}, + "cse_timeout":1800 + }`)) + require.NoError(t, err) + require.Equal(t, cloudInitConfig{Location: "config-region", RepoDepotEndpoint: "https://config", Timeout: 30 * time.Minute}, config) + }) + t.Run("non-custom cloud ignores endpoint and uses the default timeout", func(t *testing.T) { + config, err := nativeCloudInitConfig(write("public.json", `{ + "clusterConfig":{"location":"eastus"}, + "customCloudConfig":{"customCloudEnvName":"public","repoDepotEndpoint":"https://ignored"} + }`)) + require.NoError(t, err) + require.Equal(t, cloudInitConfig{Location: "eastus", Timeout: 15 * time.Minute}, config) + }) t.Run("invalid config fails", func(t *testing.T) { - path := filepath.Join(dir, "invalid.json") - require.NoError(t, os.WriteFile(path, []byte(`{"cluster_config":{"location":{}}}`), 0600)) - _, _, _, err := cloudInitializationSettings(ProvisionFlags{ProvisionConfig: path}) + _, err := nativeCloudInitConfig(write("invalid.json", `{"cluster_config":{"location":{}}}`)) require.ErrorContains(t, err, "decode provision config") }) t.Run("missing inputs fail", func(t *testing.T) { - _, _, _, err := cloudInitializationSettings(ProvisionFlags{}) - require.Error(t, err) - _, _, _, err = cloudInitializationSettings(ProvisionFlags{NBCCmd: dir}) - require.ErrorContains(t, err, "regular file") + _, err := nativeCloudInitConfig("") + require.ErrorContains(t, err, "--provision-config or --nbc-cmd is required") + _, err = nativeCloudInitConfig(filepath.Join(dir, "missing.json")) + require.ErrorContains(t, err, "read provision config") }) } func TestInitializeCloudHandoff(t *testing.T) { dir := t.TempDir() configPath := filepath.Join(dir, "config.json") + nbcPath := filepath.Join(dir, "nbc.sh") markerPath := filepath.Join(dir, "run", "init-aks-cloud.done") require.NoError(t, os.WriteFile(configPath, []byte(`{ "cluster_config":{"location":"usnat"}, "custom_cloud_config":{"custom_cloud_env_name":"AKSCustom","repo_depot_endpoint":"https://repo"} }`), 0600)) - flags := ProvisionFlags{ProvisionConfig: configPath} + require.NoError(t, os.WriteFile(nbcPath, []byte(nbcCloudInitGuard+` REPO_DEPOT_ENDPOINT='https://nbc' LOCATION='usgov' "${INIT_AKS_CLOUD_FILEPATH}"; fi;`), 0600)) + noShell := func(*exec.Cmd) error { t.Fatal("unexpected shell initialization"); return nil } + noNative := func(context.Context, cloudInitConfig) error { t.Fatal("unexpected native initialization"); return nil } - t.Run("success passes settings and creates marker", func(t *testing.T) { - app := &App{cmdRun: func(cmd *exec.Cmd) error { + t.Run("config initializes natively without the shell and creates marker", func(t *testing.T) { + var got cloudInitConfig + app := &App{cmdRun: noShell, initializeNativeCloud: func(_ context.Context, config cloudInitConfig) error { + require.NoFileExists(t, markerPath) + got = config + return nil + }} + require.NoError(t, app.initializeCloud(t.Context(), ProvisionFlags{ProvisionConfig: configPath}, "/initializer", markerPath)) + require.Equal(t, cloudInitConfig{Location: "usnat", RepoDepotEndpoint: "https://repo", Timeout: 15 * time.Minute}, got) + content, err := os.ReadFile(markerPath) + require.NoError(t, err) + require.Empty(t, content) + require.NoError(t, os.Remove(markerPath)) + }) + t.Run("native failure does not create marker", func(t *testing.T) { + app := &App{cmdRun: noShell, initializeNativeCloud: func(context.Context, cloudInitConfig) error { + return errors.New("native initialization failed") + }} + require.ErrorContains(t, app.initializeCloud(t.Context(), ProvisionFlags{ProvisionConfig: configPath}, "/initializer", markerPath), "native initialization failed") + require.NoFileExists(t, markerPath) + }) + t.Run("NBC takes precedence, passes settings and creates marker", func(t *testing.T) { + app := &App{initializeNativeCloud: noNative, cmdRun: func(cmd *exec.Cmd) error { env := envSliceToMap(cmd.Env) - require.Equal(t, "usnat", env["LOCATION"]) - require.Equal(t, "https://repo", env["REPO_DEPOT_ENDPOINT"]) - _, err := os.Stat(markerPath) - require.True(t, os.IsNotExist(err)) + require.Equal(t, "usgov", env["LOCATION"]) + require.Equal(t, "https://nbc", env["REPO_DEPOT_ENDPOINT"]) + require.NoFileExists(t, markerPath) return nil }} - require.NoError(t, app.initializeCloud(context.Background(), flags, "/initializer", markerPath)) - _, err := os.Stat(markerPath) + require.NoError(t, app.initializeCloud(t.Context(), ProvisionFlags{ProvisionConfig: configPath, NBCCmd: nbcPath}, "/initializer", markerPath)) + content, err := os.ReadFile(markerPath) require.NoError(t, err) + require.Empty(t, content) require.NoError(t, os.Remove(markerPath)) }) - t.Run("failure does not create marker", func(t *testing.T) { + t.Run("NBC failure does not create marker", func(t *testing.T) { app := &App{cmdRun: func(*exec.Cmd) error { return errors.New("initializer failed") }} - require.ErrorContains(t, app.initializeCloud(context.Background(), flags, "/initializer", markerPath), "initializer failed") - _, err := os.Stat(markerPath) - require.True(t, os.IsNotExist(err)) + require.ErrorContains(t, app.initializeCloud(t.Context(), ProvisionFlags{NBCCmd: nbcPath}, "/initializer", markerPath), "initializer failed") + require.NoFileExists(t, markerPath) }) - t.Run("missing initializer fails without a marker", func(t *testing.T) { + t.Run("missing NBC initializer fails without a marker", func(t *testing.T) { app := &App{cmdRun: cmdRunner} - require.ErrorContains(t, app.initializeCloud(context.Background(), flags, filepath.Join(dir, "missing"), markerPath), "initialize cloud") - _, err := os.Stat(markerPath) - require.True(t, os.IsNotExist(err)) + require.ErrorContains(t, app.initializeCloud(t.Context(), ProvisionFlags{NBCCmd: nbcPath}, filepath.Join(dir, "missing"), markerPath), "initialize cloud") + require.NoFileExists(t, markerPath) }) - t.Run("marker failure does not invalidate successful initialization", func(t *testing.T) { + t.Run("marker failure does not invalidate successful NBC initialization", func(t *testing.T) { blocker := filepath.Join(dir, "not-a-directory") require.NoError(t, os.WriteFile(blocker, nil, 0600)) app := &App{cmdRun: func(*exec.Cmd) error { return nil }} - require.NoError(t, app.initializeCloud(context.Background(), flags, "/initializer", filepath.Join(blocker, "done"))) + require.NoError(t, app.initializeCloud(t.Context(), ProvisionFlags{NBCCmd: nbcPath}, "/initializer", filepath.Join(blocker, "done"))) }) t.Run("old NBC does not run initializer or create marker", func(t *testing.T) { path := filepath.Join(dir, "old.sh") require.NoError(t, os.WriteFile(path, []byte("LOCATION=usnat"), 0600)) - app := &App{cmdRun: func(*exec.Cmd) error { t.Fatal("unexpected initialization"); return nil }} - require.NoError(t, app.initializeCloud(context.Background(), ProvisionFlags{NBCCmd: path}, "/initializer", markerPath)) - _, err := os.Stat(markerPath) - require.True(t, os.IsNotExist(err)) + app := &App{cmdRun: noShell, initializeNativeCloud: noNative} + require.NoError(t, app.initializeCloud(t.Context(), ProvisionFlags{ProvisionConfig: configPath, NBCCmd: path}, "/initializer", markerPath)) + require.NoFileExists(t, markerPath) }) } @@ -159,3 +193,294 @@ func TestInitializeCloudExecutesWithLiteralNBCSettings(t *testing.T) { _, err = os.Stat(markerPath) require.NoError(t, err) } + +func TestCloudInitializationCertificateModes(t *testing.T) { + cert := cloudTestCertificate(t) + for _, osCase := range []struct{ name, release, trustDir, update string }{ + {"Ubuntu", cloudTestUbuntu, "/usr/local/share/ca-certificates", "update-ca-certificates"}, + {"AzureLinux", "ID=azurelinux\n", "/etc/pki/ca-trust/source/anchors", "update-ca-trust"}, + {"Flatcar", "ID=flatcar\n", "/etc/ssl/certs", "update-ca-certificates"}, + {"ACL", "ID=azurecontainerlinux\n", "/etc/pki/ca-trust/source/anchors", "update-ca-trust"}, + } { + for _, mode := range []struct { + name, location, optIn string + eligible bool + }{ + {"not opted in", "westus2", `{"IsOptedInForRootCerts":false}`, false}, + {"rcv1p", "westus2", `{"IsOptedInForRootCerts":true}`, true}, + {"legacy", " US NAT East ", "not used", true}, + } { + t.Run(osCase.name+"/"+mode.name, func(t *testing.T) { + c := newTestCloudInitializer(t, osCase.release) + requests := serveCloudTestResponses(t, c, cert, mode.optIn) + var commands []string + run := c.run + c.run = func(cmd *exec.Cmd) error { + commands = append(commands, strings.Join(cmd.Args, " ")) + return run(cmd) + } + err := c.initialize(t.Context(), cloudInitConfig{Location: mode.location, Timeout: time.Minute}) + require.NoError(t, err) + if !mode.eligible { + require.Empty(t, commands) + require.Len(t, requests, 1) + return + } + require.Equal(t, osCase.update, commands[0]) + filename := "root.crt" + if osCase.name == "Flatcar" { + filename = "root.pem" + } + got, err := os.ReadFile(c.path(filepath.Join(osCase.trustDir, filename))) + require.NoError(t, err) + want := cert + if mode.name == "legacy" { + want = []byte(strings.TrimSuffix(string(cert), "\n") + "\r\n") + } + require.Equal(t, want, got) + assertCloudSchedule(t, c, osCase.name, commands) + if mode.name == "legacy" { + require.Len(t, requests, 1) + } else { + require.Len(t, requests, 5) + } + }) + } + } +} + +func TestCloudCertificateOptInNonTrueResponsesSkip(t *testing.T) { + for _, response := range []string{ + "not json", " ", `{}`, `null`, `[]`, `{"IsOptedInForRootCerts":false}`, + `{"IsOptedInForRootCerts":null}`, `{"IsOptedInForRootCerts":"false"}`, + `{"IsOptedInForRootCerts":"true"}`, `{"IsOptedInForRootCerts":1}`, + `{"isOptedInForRootCerts":true}`, + } { + t.Run(response, func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + requests := serveCloudTestResponses(t, c, nil, response) + c.run = func(*exec.Cmd) error { + t.Fatal("must not update trust or schedules without explicit opt-in") + return nil + } + require.NoError(t, c.initialize(t.Context(), cloudInitConfig{Location: "westus2", Timeout: time.Minute})) + require.Len(t, requests, 1) + events := c.eventLogger.Events() + require.NotEmpty(t, events) + require.Equal(t, string(helpers.EventLevelInformational), events[len(events)-1].EventLevel) + }) + } +} + +func TestCloudLegacyCertificateResponseBehavior(t *testing.T) { + for _, tc := range []struct { + name, response string + wantError bool + }{ + {"empty array", `{"Certificates":[]}`, false}, + {"non-crt file", `{"Certificates":[{"Name":"root.txt","CertBody":"payload"}]}`, false}, + {"empty body", `{"Certificates":[{"Name":"root.cer","CertBody":""}]}`, false}, + {"trust update failure", `{"Certificates":[{"Name":"root.cer","CertBody":"certificate payload"}]}`, false}, + {"invalid name", `{"Certificates":[{"Name":"../root.crt"}]}`, false}, + {"non-string name", `{"Certificates":[{"Name":123}]}`, false}, + {"missing array", `{}`, true}, + {"null array", `{"Certificates":null}`, true}, + {"missing body", `{"Certificates":[{"Name":"root.cer"}]}`, true}, + {"null body", `{"Certificates":[{"Name":"root.cer","CertBody":null}]}`, true}, + } { + t.Run(tc.name, func(t *testing.T) { + c := newTestCloudInitializer(t, "ID=azurelinux\n") + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, tc.response) + })) + defer server.Close() + c.wireEndpoint = server.URL + var commands []string + c.run = func(cmd *exec.Cmd) error { + commands = append(commands, cmd.Args[0]) + if cmd.Args[0] == "update-ca-trust" { + return errors.New("trust store update failed") + } + return nil + } + err := c.initialize(t.Context(), cloudInitConfig{Location: "usnateast", Timeout: time.Minute}) + if tc.wantError { + require.Error(t, err) + require.Empty(t, commands) + } else { + require.NoError(t, err) + require.Contains(t, commands, "crontab") + } + }) + } +} + +func TestCloudLegacyCertificateCacheWriteFailureStopsInitialization(t *testing.T) { + c := newTestCloudInitializer(t, "ID=azurelinux\n") + serveCloudTestResponses(t, c, cloudTestCertificate(t), "not used") + require.NoError(t, c.writeFile("/root/AzureCACertificates/root.crt/keep", []byte("keep"))) + c.run = func(*exec.Cmd) error { + t.Fatal("must not install certificates or schedules after a cache write failure") + return nil + } + err := c.initialize(t.Context(), cloudInitConfig{Location: "usnateast", Timeout: time.Minute}) + require.ErrorContains(t, err, "cache legacy Azure cloud certificate") +} + +func TestCloudInitializationHonorsConfiguredTimeout(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + <-r.Context().Done() + })) + defer server.Close() + c.wireEndpoint = server.URL + start := time.Now() + err := c.initialize(t.Context(), cloudInitConfig{Location: "westus2", Timeout: 25 * time.Millisecond}) + require.ErrorIs(t, err, context.DeadlineExceeded) + require.Less(t, time.Since(start), time.Second) +} + +func TestCloudInitializationStopsOnTrustAndScheduleFailures(t *testing.T) { + for _, tc := range []struct { + name, location, failedCommand, wantError string + wantCacheRefresh bool + }{ + {name: "trust store", location: "westus2", failedCommand: "update-ca-trust", wantError: "host operation failed"}, + // Like init-aks-cloud.sh, repositories are configured before the refresh schedule. + {name: "missing location", location: " \t", wantError: "requires a location", wantCacheRefresh: true}, + } { + t.Run(tc.name, func(t *testing.T) { + c := newTestCloudInitializer(t, "ID=azurelinux\n") + serveCloudTestResponses(t, c, cloudTestCertificate(t), `{"IsOptedInForRootCerts":true}`) + cacheRefreshed := false + c.run = func(cmd *exec.Cmd) error { + switch cmd.Args[0] { + case tc.failedCommand: + return errors.New("host operation failed") + case "dnf": + cacheRefreshed = true + case "crontab": + t.Fatalf("unexpected scheduling command: %s", cmd) + } + return nil + } + err := c.initialize(t.Context(), cloudInitConfig{ + Location: tc.location, RepoDepotEndpoint: "https://repo.example/ubuntu", Timeout: time.Minute, + }) + require.ErrorContains(t, err, tc.wantError) + require.Equal(t, tc.wantCacheRefresh, cacheRefreshed) + }) + } +} + +func TestCloudInitializationSchedulesRefreshAfterRepositories(t *testing.T) { + t.Run("success", func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + serveCloudTestResponses(t, c, cloudTestCertificate(t), `{"IsOptedInForRootCerts":true}`) + run := c.run + var commands []string + c.run = func(cmd *exec.Cmd) error { + commands = append(commands, cmd.Args[0]) + return run(cmd) + } + require.NoError(t, c.initialize(t.Context(), cloudInitConfig{ + Location: "westus2", RepoDepotEndpoint: c.wireEndpoint, Timeout: time.Minute, + })) + cache := slices.Index(commands, "apt-get") + schedule := slices.Index(commands, "crontab") + require.NotEqual(t, -1, cache) + require.Greater(t, schedule, cache) + }) + t.Run("repository failure leaves no schedule", func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + serveCloudTestResponses(t, c, cloudTestCertificate(t), `{"IsOptedInForRootCerts":true}`) + run := c.run + c.run = func(cmd *exec.Cmd) error { + require.NotEqual(t, "crontab", cmd.Args[0], "a failed initialization must not leave a refresh schedule behind") + return run(cmd) + } + err := c.initialize(t.Context(), cloudInitConfig{ + Location: "westus2", RepoDepotEndpoint: "not-a-url", Timeout: time.Minute, + }) + require.ErrorContains(t, err, "invalid RepoDepot endpoint") + }) +} + +func TestCloudInitializationContinuesAfterCronFailures(t *testing.T) { + for _, failedArg := range []string{"-l", "-"} { + t.Run(failedArg, func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + serveCloudTestResponses(t, c, cloudTestCertificate(t), `{"IsOptedInForRootCerts":true}`) + run := c.run + writes, cacheUpdates := 0, 0 + c.run = func(cmd *exec.Cmd) error { + if cmd.Args[0] == "crontab" { + if cmd.Args[1] == "-" { + writes++ + } + if cmd.Args[1] == failedArg { + return errors.New("crontab operation failed") + } + } + if cmd.Args[0] == "apt-get" { + cacheUpdates++ + } + return run(cmd) + } + require.NoError(t, c.initialize(t.Context(), cloudInitConfig{ + Location: "westus2", RepoDepotEndpoint: c.wireEndpoint, Timeout: time.Minute, + })) + require.Equal(t, 1, writes) + require.Equal(t, 1, cacheUpdates) + }) + } +} + +func TestCloudInitializationContinuesAfterCacheFailures(t *testing.T) { + for _, tc := range []struct{ id, release, command string }{ + {config.OSReleaseIDUbuntu, cloudTestUbuntu, "apt-get"}, + {config.OSReleaseIDAzureLinux, "ID=azurelinux\n", "dnf"}, + } { + t.Run(tc.id, func(t *testing.T) { + c := newTestCloudInitializer(t, tc.release) + serveCloudTestResponses(t, c, cloudTestCertificate(t), `{"IsOptedInForRootCerts":true}`) + run := c.run + attempts, schedules := 0, 0 + c.run = func(cmd *exec.Cmd) error { + switch cmd.Args[0] { + case tc.command: + attempts++ + return errors.New("cache refresh failed") + case "crontab": + schedules++ + } + return run(cmd) + } + require.NoError(t, c.initialize(t.Context(), cloudInitConfig{ + Location: "westus2", RepoDepotEndpoint: c.wireEndpoint, Timeout: time.Minute, + })) + require.Equal(t, cloudRequestAttempts, attempts) + require.NotZero(t, schedules, "cache refresh failures must not skip the refresh schedule") + levels := make(map[string]string) + for _, event := range c.eventLogger.Events() { + levels[event.TaskName] = event.EventLevel + } + require.Equal(t, "Error", levels["AKS.AKSNodeController.CloudRepositoryInitialization"]) + require.Equal(t, "Informational", levels["AKS.AKSNodeController.CloudInitialization"]) + }) + } +} + +func TestCloudInitializationCacheCancellationStopsInitialization(t *testing.T) { + c := newTestCloudInitializer(t, "ID=azurelinux\n") + serveCloudTestResponses(t, c, nil, `{"IsOptedInForRootCerts":false}`) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + c.run = func(cmd *exec.Cmd) error { + require.Equal(t, "dnf", cmd.Args[0]) + cancel() + return ctx.Err() + } + err := c.initialize(ctx, cloudInitConfig{Location: "westus2", RepoDepotEndpoint: c.wireEndpoint, Timeout: time.Minute}) + require.ErrorIs(t, err, context.Canceled) +} diff --git a/aks-node-controller/cloud_refresh.go b/aks-node-controller/cloud_refresh.go new file mode 100644 index 00000000000..4a183a62b19 --- /dev/null +++ b/aks-node-controller/cloud_refresh.go @@ -0,0 +1,61 @@ +package main + +import ( + "context" + "errors" + "log/slog" + "strings" + "time" + "unicode" +) + +const cloudRefreshTimeout = 15 * time.Minute + +func (a *App) runCloudCertificateRefresh(ctx context.Context, location string) error { + if strings.TrimSpace(location) == "" { + return errors.New("cloud certificate refresh requires a location") + } + var err error + if a.refreshCloudCertificates != nil { + err = a.refreshCloudCertificates(ctx, location) + } else { + initializer := newCloudInitializer(a) + defer initializer.close() + err = initializer.refreshCertificates(ctx, location) + } + if err != nil { + slog.Error("Azure cloud certificate refresh failed", "error", err) + } + return err +} + +func (c *cloudInitializer) refreshCertificates(ctx context.Context, location string) error { + refreshCtx, cancel := context.WithTimeout(ctx, cloudRefreshTimeout) + defer cancel() + return c.withEvent("CloudCertificateRefresh", func() error { + platform, err := c.platform() + if err != nil { + return err + } + _, err = c.refresh(refreshCtx, platform, location) + return err + }) +} + +func normalizeCloudLocation(location string) (string, error) { + location = strings.ToLower(strings.Map(func(r rune) rune { + if unicode.IsSpace(r) { + return -1 + } + return r + }, location)) + if strings.IndexFunc(location, func(r rune) bool { + return !strings.ContainsRune("abcdefghijklmnopqrstuvwxyz0123456789-", r) + }) != -1 { + return "", errors.New("cloud location contains unsupported characters") + } + if location == "" { + slog.Warn("Azure cloud location is empty, using rcv1p certificate endpoints") + } + return location, nil +} diff --git a/aks-node-controller/cloud_refresh_schedule.go b/aks-node-controller/cloud_refresh_schedule.go new file mode 100644 index 00000000000..e3502f198a3 --- /dev/null +++ b/aks-node-controller/cloud_refresh_schedule.go @@ -0,0 +1,105 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log/slog" + "os" + "path/filepath" + "strconv" + "strings" + + "github.com/Azure/agentbaker/aks-node-controller/config" +) + +const cloudRefreshService = `[Unit] +Description=Refresh Azure Custom Cloud CA certificates +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +ExecStart=%s +` + +const cloudRefreshTimer = `[Unit] +Description=Daily refresh of Azure Custom Cloud CA certificates + +[Timer] +OnCalendar=19:00 +Persistent=true +RandomizedDelaySec=300 + +[Install] +WantedBy=timers.target +` + +func (c *cloudInitializer) installRefreshSchedule(ctx context.Context, platform cloudPlatform, location string) error { + if location == "" { + return errors.New("cloud certificate refresh requires a location") + } + binary := c.executable + if binary == "" { + var err error + binary, err = os.Executable() + if err != nil { + return err + } + } + if !filepath.IsAbs(binary) || strings.ContainsAny(binary, "\"\\%\r\n") { + return errors.New("invalid executable path for Azure cloud certificate refresh") + } + // Schedule the running binary because it implements refresh-cloud-certificates. + command := strconv.Quote(binary) + " refresh-cloud-certificates --location " + strconv.Quote(location) + if platform.ID == config.OSReleaseIDFlatcar || platform.ID == config.OSReleaseIDAzureContainerLinux { + return c.installSystemdRefresh(ctx, command) + } + return c.installCronRefresh(ctx, command) +} + +func (c *cloudInitializer) installSystemdRefresh(ctx context.Context, command string) error { + if err := c.writeFile("/etc/systemd/system/azure-ca-refresh.service", []byte(fmt.Sprintf(cloudRefreshService, command))); err != nil { + return err + } + if err := c.writeFile("/etc/systemd/system/azure-ca-refresh.timer", []byte(cloudRefreshTimer)); err != nil { + return err + } + if _, err := c.command(ctx, nil, "systemctl", "daemon-reload"); err != nil { + return err + } + _, err := c.command(ctx, nil, "systemctl", "enable", "--now", "azure-ca-refresh.timer") + return err +} + +func (c *cloudInitializer) installCronRefresh(ctx context.Context, command string) error { + existing, err := c.command(ctx, nil, "crontab", "-l") + if err != nil { + if contextErr := ctx.Err(); contextErr != nil { + return contextErr + } + var exitErr interface{ ExitCode() int } + if !errors.As(err, &exitErr) || exitErr.ExitCode() != 1 || !strings.Contains(err.Error(), "no crontab for") { + slog.Warn("could not read existing crontab, continuing with an empty crontab", "error", err) + } + existing = nil + } + var lines []string + for line := range strings.SplitSeq(string(existing), "\n") { + if strings.TrimSpace(line) == "" || + strings.Contains(line, "init-aks-cloud.sh") && strings.Contains(line, "ca-refresh") || + strings.Contains(line, "refresh-cloud-certificates") && strings.Contains(line, "aks-node-controller") { + continue + } + lines = append(lines, line) + } + lines = append(lines, "0 19 * * * "+command) + _, err = c.command(ctx, []byte(strings.Join(lines, "\n")+"\n"), "crontab", "-") + if err != nil { + if contextErr := ctx.Err(); contextErr != nil { + return contextErr + } + slog.Warn("could not install Azure cloud certificate refresh cron job, continuing cloud initialization", "error", err) + } + return nil +} diff --git a/aks-node-controller/cloud_refresh_schedule_test.go b/aks-node-controller/cloud_refresh_schedule_test.go new file mode 100644 index 00000000000..2e611ace9cb --- /dev/null +++ b/aks-node-controller/cloud_refresh_schedule_test.go @@ -0,0 +1,140 @@ +package main + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "os/exec" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/Azure/agentbaker/aks-node-controller/config" +) + +func assertCloudSchedule(t *testing.T, c *cloudInitializer, osName string, commands []string) { + t.Helper() + if osName != "Flatcar" && osName != "ACL" { + require.Contains(t, commands, "crontab -") + return + } + require.Contains(t, commands, "systemctl enable --now azure-ca-refresh.timer") + service, err := os.ReadFile(c.path("/etc/systemd/system/azure-ca-refresh.service")) + require.NoError(t, err) + require.Contains(t, string(service), vhdBinaryPath) + require.Contains(t, string(service), "refresh-cloud-certificates") + require.NotContains(t, string(service), "init-aks-cloud.sh") +} + +func TestCloudRefreshScheduleReplacesLegacyCron(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + cron := "5 2 * * * /usr/bin/keep-me\n" + + "0 19 * * * \"/opt/azure/containers/init-aks-cloud.sh\" ca-refresh \"usnateast\"\n" + c.run = func(cmd *exec.Cmd) error { + switch strings.Join(cmd.Args, " ") { + case "crontab -l": + _, _ = io.WriteString(cmd.Stdout, cron) + case "crontab -": + data, err := io.ReadAll(cmd.Stdin) + require.NoError(t, err) + cron = string(data) + default: + t.Fatalf("unexpected scheduling command: %s", cmd) + } + return nil + } + for range 2 { + require.NoError(t, c.installRefreshSchedule(t.Context(), cloudPlatform{ID: config.OSReleaseIDUbuntu}, "usnateast")) + } + require.Contains(t, cron, "5 2 * * * /usr/bin/keep-me") + require.NotContains(t, cron, "init-aks-cloud.sh") + require.Equal(t, 1, strings.Count(cron, "refresh-cloud-certificates")) + require.Contains(t, cron, fmt.Sprintf(`0 19 * * * "%s" refresh-cloud-certificates --location "usnateast"`, vhdBinaryPath)) +} + +func TestCloudRefreshScheduleCrontabErrors(t *testing.T) { + for _, tc := range []struct { + name, stderr string + }{ + {"no existing crontab", "no crontab for root"}, + {"permission denied", "permission denied"}, + } { + t.Run(tc.name, func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + writes := 0 + c.run = func(cmd *exec.Cmd) error { + if cmd.Args[1] == "-l" { + _, _ = io.WriteString(cmd.Stderr, tc.stderr) + return &testExitError{Code: 1} + } + writes++ + return nil + } + err := c.installRefreshSchedule(t.Context(), cloudPlatform{ID: config.OSReleaseIDUbuntu}, "westus2") + require.NoError(t, err) + require.Equal(t, 1, writes) + }) + } +} + +func TestCloudCronInstallationFailureIsLogged(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + logs := installLogCapturer(t) + c.run = func(cmd *exec.Cmd) error { + if cmd.Args[1] == "-" { + return errors.New("cron installation failed") + } + return nil + } + require.NoError(t, c.installRefreshSchedule(t.Context(), cloudPlatform{ID: config.OSReleaseIDUbuntu}, "westus2")) + require.Contains(t, fmt.Sprint(logs.getRecords()), "cron installation failed") +} + +func TestCloudCronCancellationIsNotIgnored(t *testing.T) { + for _, canceledArg := range []string{"-l", "-"} { + t.Run(canceledArg, func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + c.run = func(cmd *exec.Cmd) error { + if cmd.Args[1] == canceledArg { + cancel() + return ctx.Err() + } + return nil + } + require.ErrorIs(t, c.installRefreshSchedule(ctx, cloudPlatform{ID: config.OSReleaseIDUbuntu}, "westus2"), context.Canceled) + }) + } +} + +func TestCloudCronDeadlineIsNotIgnored(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + ctx, cancel := context.WithDeadline(t.Context(), time.Now().Add(-time.Second)) + defer cancel() + c.run = func(*exec.Cmd) error { + t.Fatal("an expired context must not execute crontab") + return nil + } + require.ErrorIs(t, c.installRefreshSchedule(ctx, cloudPlatform{ID: config.OSReleaseIDUbuntu}, "westus2"), context.DeadlineExceeded) +} + +func TestCloudSystemdRefreshFailuresRemainFatal(t *testing.T) { + for _, failedArgs := range []string{"daemon-reload", "enable --now azure-ca-refresh.timer"} { + t.Run(failedArgs, func(t *testing.T) { + c := newTestCloudInitializer(t, "ID=flatcar\n") + c.run = func(cmd *exec.Cmd) error { + if strings.Join(cmd.Args[1:], " ") == failedArgs { + return errors.New("systemd operation failed") + } + return nil + } + require.ErrorContains(t, c.installRefreshSchedule(t.Context(), cloudPlatform{ID: config.OSReleaseIDFlatcar}, "westus2"), + "systemd operation failed") + }) + } +} diff --git a/aks-node-controller/cloud_refresh_test.go b/aks-node-controller/cloud_refresh_test.go new file mode 100644 index 00000000000..06c98447237 --- /dev/null +++ b/aks-node-controller/cloud_refresh_test.go @@ -0,0 +1,48 @@ +package main + +import ( + "context" + "errors" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestNormalizeCloudLocation(t *testing.T) { + location, err := normalizeCloudLocation(" US Sec East \t\n") + require.NoError(t, err) + require.Equal(t, "usseceast", location) + for _, value := range []string{`westus";echo bad`, "westus%bad", "westus\\bad"} { + _, err = normalizeCloudLocation(value) + require.Error(t, err) + } +} + +func TestCloudCertificateRefreshCommand(t *testing.T) { + for _, tc := range []struct { + name string + args []string + err error + wantCall bool + wantError bool + }{ + {"valid", []string{"--location", "usnateast"}, nil, true, false}, + {"refresh failure", []string{"--location", "usnateast"}, errors.New("refresh failed"), true, true}, + {"missing location", nil, nil, false, true}, + {"empty location", []string{"--location", " "}, nil, false, true}, + {"unexpected argument", []string{"--location", "usnateast", "extra"}, nil, false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + tt := NewTestApp(t, TestAppConfig{}) + called := false + tt.App.refreshCloudCertificates = func(_ context.Context, location string) error { + called = true + require.Equal(t, "usnateast", location) + return tc.err + } + code := tt.App.Run(t.Context(), append([]string{"aks-node-controller", "refresh-cloud-certificates"}, tc.args...)) + require.Equal(t, tc.wantCall, called) + require.Equal(t, tc.wantError, code != 0) + }) + } +} diff --git a/aks-node-controller/cloud_repositories.go b/aks-node-controller/cloud_repositories.go new file mode 100644 index 00000000000..c465240ddde --- /dev/null +++ b/aks-node-controller/cloud_repositories.go @@ -0,0 +1,233 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log/slog" + "net/http" + "net/url" + "os" + "path/filepath" + "regexp" + "runtime" + "strings" + "time" + + "github.com/Azure/agentbaker/aks-node-controller/common" + "github.com/Azure/agentbaker/aks-node-controller/config" +) + +const cloudRepoSchemeHTTP = "http" + +const cloudRepoSchemeHTTPS = "https" + +const ubuntuCloudSource = ` +Types: deb +URIs: %s/ubuntu +Suites: %s %s-updates %s-backports %s-security +Components: main universe restricted multiverse +Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg +` + +const microsoftCloudSource = ` +Types: deb +URIs: %s +Suites: %s +Components: main +Architectures: %s +Signed-By: %s +` + +const azureLinuxCloudRepo = `[azurelinux-official-%s] +name=Azure Linux Official %s $releasever $basearch +baseurl=%s/azurelinux/$releasever/prod/%s/$basearch +gpgkey=file:///etc/pki/rpm-gpg/MICROSOFT-RPM-GPG-KEY +gpgcheck=1 +repo_gpgcheck=1 +enabled=1 +skip_if_unavailable=True +sslverify=1 +` + +var errCloudRepositoryCacheRefresh = errors.New("refresh RepoDepot package cache") + +func (c *cloudInitializer) initializeRepositories(ctx context.Context, platform cloudPlatform, endpoint string) error { + if endpoint == "" { + slog.Info("RepoDepot endpoint is empty, skipping repository initialization") + return nil + } + endpoint = strings.TrimSuffix(strings.TrimRight(endpoint, "/"), "/ubuntu") + parsed, err := url.Parse(endpoint) + if err != nil || parsed.Host == "" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" || + (parsed.Scheme != cloudRepoSchemeHTTP && parsed.Scheme != cloudRepoSchemeHTTPS) || strings.ContainsAny(endpoint, "\r\n\t ") { + return errors.New("invalid RepoDepot endpoint") + } + switch platform.ID { + case config.OSReleaseIDUbuntu: + if err := c.initializeUbuntuRepositories(ctx, platform, endpoint); err != nil { + return err + } + return c.updateRepositoryCache(ctx, "apt-get", "update") + case config.OSReleaseIDAzureLinux: + if err := c.initializeAzureLinuxRepositories(endpoint); err != nil { + return err + } + return c.updateRepositoryCache(ctx, "dnf", "makecache", "-y") + default: + slog.Info("RepoDepot initialization is not needed on immutable OS", "OS", platform.ID) + return nil + } +} + +func (c *cloudInitializer) repositoryGET(ctx context.Context, endpoint string) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + resp, err := c.repoClient.Do(req) + if err != nil { + return nil, err + } + body, err := readCloudResponse(resp) + if err != nil { + return nil, err + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, fmt.Errorf("RepoDepot request returned HTTP %d", resp.StatusCode) + } + return body, nil +} + +func (c *cloudInitializer) initializeUbuntuRepositories(ctx context.Context, platform cloudPlatform, endpoint string) error { + if platform.Version == "" || platform.Codename == "" || + strings.ContainsAny(platform.Version+platform.Codename, "\r\n\t ") { + return errors.New("missing valid Ubuntu VERSION_ID or VERSION_CODENAME") + } + if err := c.copyOpenSSLBundle(); err != nil { + return fmt.Errorf("copy Ubuntu CA bundle: %w", err) + } + if err := c.backupUbuntuSources(); err != nil { + return err + } + mainSource := fmt.Sprintf(ubuntuCloudSource, + endpoint, platform.Codename, platform.Codename, platform.Codename, platform.Codename) + if err := c.writeFile(defaultAptSourcesDir+"/ubuntu.sources", []byte(mainSource)); err != nil { + return err + } + microsoftSource := endpoint + "/microsoft/ubuntu/" + platform.Version + "/prod" + if _, err := c.repositoryGET(ctx, microsoftSource); err != nil { + return fmt.Errorf("check Ubuntu Microsoft repository: %w", err) + } + keyPaths, err := c.ubuntuRepositoryKeyrings(ctx, endpoint) + if err != nil { + return err + } + microsoftConfig := fmt.Sprintf(microsoftCloudSource, + microsoftSource, platform.Codename, runtime.GOARCH, strings.Join(keyPaths, " ")) + for _, name := range []string{"microsoft-prod", "microsoft-prod-testing"} { + if err := c.writeFile(defaultAptSourcesDir+"/"+name+".sources", []byte(microsoftConfig)); err != nil { + return err + } + } + return nil +} + +func (c *cloudInitializer) backupUbuntuSources() error { + sourcesDir, backupDir := c.path(defaultAptSourcesDir), c.path("/etc/apt/backup") + if err := os.MkdirAll(sourcesDir, 0o755); err != nil { + return err + } + if err := os.MkdirAll(backupDir, 0o755); err != nil { + return err + } + sources, err := filepath.Glob(filepath.Join(sourcesDir, "*")) + if err != nil { + return err + } + sources = append(sources, c.path("/etc/apt/sources.list")) + for _, source := range sources { + info, err := os.Stat(source) + if errors.Is(err, os.ErrNotExist) { + continue + } + if err != nil { + return err + } + if info.Mode().IsRegular() { + if err := os.Rename(source, filepath.Join(backupDir, filepath.Base(source))); err != nil { + return err + } + } + } + return nil +} + +func (c *cloudInitializer) ubuntuRepositoryKeyrings(ctx context.Context, endpoint string) ([]string, error) { + var keyPaths []string + for _, key := range []string{"microsoft.asc", "msopentech.asc"} { + body, err := c.repositoryGET(ctx, endpoint+"/keys/"+key) + if err != nil { + return nil, fmt.Errorf("download RepoDepot key %s: %w", key, err) + } + keyring, err := c.command(ctx, body, "gpg", "--dearmor") + if err != nil { + return nil, err + } + if len(keyring) == 0 { + return nil, fmt.Errorf("RepoDepot key %s produced an empty keyring", key) + } + path := "/etc/apt/keyrings/" + key + ".gpg" + if err := c.writeFile(path, keyring); err != nil { + return nil, err + } + keyPaths = append(keyPaths, path) + } + return keyPaths, nil +} + +func (c *cloudInitializer) initializeAzureLinuxRepositories(endpoint string) error { + paths, err := filepath.Glob(c.path(defaultYumReposDir + "/azurelinux*")) + if err != nil { + return err + } + for _, path := range paths { + if err := os.Remove(path); err != nil { + return err + } + } + for _, repo := range []string{"amd", "base", "cloud-native", "extended", "ms-non-oss", "ms-oss", "nvidia"} { + content := fmt.Sprintf(azureLinuxCloudRepo, + repo, repo, endpoint, repo) + if err := c.writeFile(defaultYumReposDir+"/azurelinux-"+repo+".repo", []byte(content)); err != nil { + return err + } + } + return nil +} + +func (c *cloudInitializer) updateRepositoryCache(ctx context.Context, name string, args ...string) error { + attempt := 0 + dnfError := regexp.MustCompile(`(?m)^([WE]:.*)|([eE]rr.*)$`) + _, err := common.RetryFetch(ctx, cloudRequestAttempts, nil, func(ctx context.Context) (struct{}, error) { + if attempt > 0 { + if err := c.wait(ctx, 5*time.Second); err != nil { + return struct{}{}, err + } + } + attempt++ + output, err := c.command(ctx, nil, name, args...) + slog.Info("refreshing RepoDepot package cache", "command", name, "attempt", attempt, "output", string(output)) + if err == nil && name == "dnf" && dnfError.Match(output) { + err = errors.New("dnf reported repository metadata errors") + } + return struct{}{}, err + }) + if err != nil { + if contextErr := ctx.Err(); contextErr != nil { + return fmt.Errorf("refresh RepoDepot package cache: %w", contextErr) + } + return fmt.Errorf("%w: %w", errCloudRepositoryCacheRefresh, err) + } + return nil +} diff --git a/aks-node-controller/cloud_repositories_configuration_test.go b/aks-node-controller/cloud_repositories_configuration_test.go new file mode 100644 index 00000000000..1336c844379 --- /dev/null +++ b/aks-node-controller/cloud_repositories_configuration_test.go @@ -0,0 +1,76 @@ +package main + +import ( + "os" + "os/exec" + "runtime" + "strings" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/Azure/agentbaker/aks-node-controller/config" +) + +func TestCloudUbuntuRepositoryConfiguration(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + serveCloudTestResponses(t, c, nil, `{"IsOptedInForRootCerts":false}`) + require.NoError(t, c.writeFile("/etc/apt/sources.list", []byte("original ubuntu sources"))) + require.NoError(t, c.writeFile(defaultAptSourcesDir+"/original.sources", []byte("original extra sources"))) + var commands []string + run := c.run + c.run = func(cmd *exec.Cmd) error { + commands = append(commands, strings.Join(cmd.Args, " ")) + return run(cmd) + } + platform, err := c.platform() + require.NoError(t, err) + require.NoError(t, c.initializeRepositories(t.Context(), platform, c.wireEndpoint+"/ubuntu/")) + require.Equal(t, []string{"gpg --dearmor", "gpg --dearmor", "apt-get update"}, commands) + backup, err := os.ReadFile(c.path("/etc/apt/backup/sources.list")) + require.NoError(t, err) + require.Equal(t, "original ubuntu sources", string(backup)) + backup, err = os.ReadFile(c.path("/etc/apt/backup/original.sources")) + require.NoError(t, err) + require.Equal(t, "original extra sources", string(backup)) + source, err := os.ReadFile(c.path(defaultAptSourcesDir + "/ubuntu.sources")) + require.NoError(t, err) + require.Contains(t, string(source), "URIs: "+c.wireEndpoint+"/ubuntu\n") + require.Contains(t, string(source), "Suites: jammy jammy-updates jammy-backports jammy-security") + for _, name := range []string{"microsoft-prod", "microsoft-prod-testing"} { + source, err := os.ReadFile(c.path(defaultAptSourcesDir + "/" + name + ".sources")) + require.NoError(t, err) + require.Contains(t, string(source), c.wireEndpoint+"/microsoft/ubuntu/22.04/prod") + require.Contains(t, string(source), "Architectures: "+runtime.GOARCH) + require.Contains(t, string(source), "Signed-By: /etc/apt/keyrings/microsoft.asc.gpg /etc/apt/keyrings/msopentech.asc.gpg") + } + for _, name := range []string{"microsoft.asc", "msopentech.asc"} { + key, err := os.ReadFile(c.path("/etc/apt/keyrings/" + name + ".gpg")) + require.NoError(t, err) + require.Equal(t, "dearmored-key", string(key)) + } +} + +func TestCloudRPMRepositoryConfiguration(t *testing.T) { + c := newTestCloudInitializer(t, "ID=azurelinux\n") + require.NoError(t, c.writeFile(defaultYumReposDir+"/keep.repo", []byte("keep this repository"))) + require.NoError(t, c.writeFile(defaultYumReposDir+"/azurelinux-old.repo", []byte("obsolete"))) + var commands []string + c.run = func(cmd *exec.Cmd) error { + commands = append(commands, strings.Join(cmd.Args, " ")) + return nil + } + require.NoError(t, c.initializeRepositories(t.Context(), cloudPlatform{ID: config.OSReleaseIDAzureLinux}, "https://repo.example/ubuntu")) + require.Equal(t, []string{"dnf makecache -y"}, commands) + _, statErr := os.Stat(c.path(defaultYumReposDir + "/azurelinux-old.repo")) + require.ErrorIs(t, statErr, os.ErrNotExist) + for _, repo := range []string{"amd", "base", "cloud-native", "extended", "ms-non-oss", "ms-oss", "nvidia"} { + source, err := os.ReadFile(c.path(defaultYumReposDir + "/azurelinux-" + repo + ".repo")) + require.NoError(t, err) + require.Contains(t, string(source), "https://repo.example/azurelinux/$releasever/prod/"+repo+"/$basearch") + require.Contains(t, string(source), "gpgcheck=1\nrepo_gpgcheck=1") + } + keep, err := os.ReadFile(c.path(defaultYumReposDir + "/keep.repo")) + require.NoError(t, err) + require.Equal(t, "keep this repository", string(keep)) +} diff --git a/aks-node-controller/cloud_repositories_integration_test.go b/aks-node-controller/cloud_repositories_integration_test.go new file mode 100644 index 00000000000..4e35635d020 --- /dev/null +++ b/aks-node-controller/cloud_repositories_integration_test.go @@ -0,0 +1,91 @@ +package main + +import ( + "os" + "os/exec" + "runtime" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestCloudUbuntuRepositoryInitializationIndependentOfOptIn(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + serveCloudTestResponses(t, c, nil, `{"IsOptedInForRootCerts":false}`) + require.NoError(t, c.writeFile("/etc/apt/sources.list", []byte("original ubuntu sources"))) + require.NoError(t, c.writeFile(defaultAptSourcesDir+"/original.sources", []byte("original extra sources"))) + var commands []string + run := c.run + c.run = func(cmd *exec.Cmd) error { + commands = append(commands, strings.Join(cmd.Args, " ")) + return run(cmd) + } + require.NoError(t, c.initialize(t.Context(), cloudInitConfig{ + Location: "westus2", RepoDepotEndpoint: c.wireEndpoint + "/ubuntu/", Timeout: time.Minute, + })) + require.Equal(t, []string{"gpg --dearmor", "gpg --dearmor", "apt-get update"}, commands) + backup, err := os.ReadFile(c.path("/etc/apt/backup/sources.list")) + require.NoError(t, err) + require.Equal(t, "original ubuntu sources", string(backup)) + backup, err = os.ReadFile(c.path("/etc/apt/backup/original.sources")) + require.NoError(t, err) + require.Equal(t, "original extra sources", string(backup)) + source, err := os.ReadFile(c.path(defaultAptSourcesDir + "/ubuntu.sources")) + require.NoError(t, err) + require.Contains(t, string(source), "URIs: "+c.wireEndpoint+"/ubuntu\n") + require.Contains(t, string(source), "Suites: jammy jammy-updates jammy-backports jammy-security") + for _, name := range []string{"microsoft-prod", "microsoft-prod-testing"} { + source, err := os.ReadFile(c.path(defaultAptSourcesDir + "/" + name + ".sources")) + require.NoError(t, err) + require.Contains(t, string(source), c.wireEndpoint+"/microsoft/ubuntu/22.04/prod") + require.Contains(t, string(source), "Architectures: "+runtime.GOARCH) + require.Contains(t, string(source), "Signed-By: /etc/apt/keyrings/microsoft.asc.gpg /etc/apt/keyrings/msopentech.asc.gpg") + } + for _, name := range []string{"microsoft.asc", "msopentech.asc"} { + key, err := os.ReadFile(c.path("/etc/apt/keyrings/" + name + ".gpg")) + require.NoError(t, err) + require.Equal(t, "dearmored-key", string(key)) + } +} + +func TestCloudRPMRepositoryInitializationIndependentOfOptIn(t *testing.T) { + c := newTestCloudInitializer(t, "ID=azurelinux\n") + serveCloudTestResponses(t, c, nil, `{"IsOptedInForRootCerts":false}`) + require.NoError(t, c.writeFile(defaultYumReposDir+"/keep.repo", []byte("keep this repository"))) + require.NoError(t, c.writeFile(defaultYumReposDir+"/azurelinux-old.repo", []byte("obsolete"))) + var commands []string + c.run = func(cmd *exec.Cmd) error { + commands = append(commands, strings.Join(cmd.Args, " ")) + return nil + } + require.NoError(t, c.initialize(t.Context(), cloudInitConfig{ + Location: "westus2", RepoDepotEndpoint: "https://repo.example/ubuntu", Timeout: time.Minute, + })) + require.Equal(t, []string{"dnf makecache -y"}, commands) + _, statErr := os.Stat(c.path(defaultYumReposDir + "/azurelinux-old.repo")) + require.ErrorIs(t, statErr, os.ErrNotExist) + for _, repo := range []string{"amd", "base", "cloud-native", "extended", "ms-non-oss", "ms-oss", "nvidia"} { + source, err := os.ReadFile(c.path(defaultYumReposDir + "/azurelinux-" + repo + ".repo")) + require.NoError(t, err) + require.Contains(t, string(source), "https://repo.example/azurelinux/$releasever/prod/"+repo+"/$basearch") + require.Contains(t, string(source), "gpgcheck=1\nrepo_gpgcheck=1") + } + keep, err := os.ReadFile(c.path(defaultYumReposDir + "/keep.repo")) + require.NoError(t, err) + require.Equal(t, "keep this repository", string(keep)) +} + +func TestCloudRepositorySetupFailureStillStopsInitialization(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + serveCloudTestResponses(t, c, nil, `{"IsOptedInForRootCerts":false}`) + c.run = func(*exec.Cmd) error { + t.Fatal("an invalid endpoint must not reach package cache refresh") + return nil + } + err := c.initialize(t.Context(), cloudInitConfig{ + Location: "westus2", RepoDepotEndpoint: "not-a-url", Timeout: time.Minute, + }) + require.ErrorContains(t, err, "invalid RepoDepot endpoint") +} diff --git a/aks-node-controller/cloud_repositories_test.go b/aks-node-controller/cloud_repositories_test.go new file mode 100644 index 00000000000..393642a52f3 --- /dev/null +++ b/aks-node-controller/cloud_repositories_test.go @@ -0,0 +1,83 @@ +package main + +import ( + "context" + "errors" + "io" + "os/exec" + "strconv" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/Azure/agentbaker/aks-node-controller/config" +) + +func TestCloudRepositoriesSkipEmptyEndpointAndImmutableOS(t *testing.T) { + for _, tc := range []struct{ id, endpoint string }{ + {config.OSReleaseIDUbuntu, ""}, {config.OSReleaseIDAzureLinux, ""}, + {config.OSReleaseIDFlatcar, "https://repo.example"}, {config.OSReleaseIDAzureContainerLinux, "https://repo.example"}, + } { + t.Run(tc.id+"/"+tc.endpoint, func(t *testing.T) { + c := newTestCloudInitializer(t, "ID="+tc.id+"\n") + c.run = func(*exec.Cmd) error { + t.Fatal("no repository commands expected") + return nil + } + require.NoError(t, c.initializeRepositories(t.Context(), cloudPlatform{ID: tc.id}, tc.endpoint)) + }) + } +} + +func TestCloudRepositoryEndpointValidation(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + for _, endpoint := range []string{ + "not-a-url", "file:///etc/apt", "https://repo.example\nSigned-By: bad", "https://user:password@repo.example", + "https://repo.example?query=1", "https://repo.example/#fragment", + } { + require.ErrorContains(t, c.initializeRepositories(t.Context(), cloudPlatform{ID: config.OSReleaseIDUbuntu}, endpoint), "invalid RepoDepot endpoint") + } +} + +func TestCloudRepositoryCacheRetriesAndFailsExplicitly(t *testing.T) { + for _, name := range []string{"apt-get", "dnf"} { + for _, recoverAfter := range []int{2, cloudRequestAttempts + 1} { + t.Run(name+"/"+strconv.Itoa(recoverAfter), func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + attempts := 0 + c.run = func(cmd *exec.Cmd) error { + attempts++ + if attempts < recoverAfter { + if name == "dnf" { + _, _ = io.WriteString(cmd.Stderr, "Error: repository metadata is unavailable\n") + return nil + } + return errors.New("cache refresh failed") + } + return nil + } + err := c.updateRepositoryCache(t.Context(), name, "update") + if recoverAfter > cloudRequestAttempts { + require.ErrorContains(t, err, "refresh RepoDepot package cache") + require.ErrorIs(t, err, errCloudRepositoryCacheRefresh) + require.Equal(t, cloudRequestAttempts, attempts) + } else { + require.NoError(t, err) + require.Equal(t, recoverAfter, attempts) + } + }) + } + } + t.Run("canceled", func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + c.run = func(*exec.Cmd) error { + t.Fatal("canceled context must not execute a command") + return nil + } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + err := c.updateRepositoryCache(ctx, "apt-get", "update") + require.ErrorIs(t, err, context.Canceled) + require.NotErrorIs(t, err, errCloudRepositoryCacheRefresh) + }) +} diff --git a/aks-node-controller/cloud_runtime.go b/aks-node-controller/cloud_runtime.go new file mode 100644 index 00000000000..cc8a193441c --- /dev/null +++ b/aks-node-controller/cloud_runtime.go @@ -0,0 +1,196 @@ +package main + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "os" + "os/exec" + "path/filepath" + "strings" + "syscall" + "time" + + "github.com/Azure/agentbaker/aks-node-controller/common" + "github.com/Azure/agentbaker/aks-node-controller/config" + "github.com/Azure/agentbaker/aks-node-controller/helpers" +) + +const cloudResponseLimit = 8 << 20 + +const ( + cloudCommandTimeout = 2 * time.Minute + cloudCommandWaitDelay = 5 * time.Second +) + +type cloudPlatform struct { + ID, Version, Codename string +} + +type cloudInitializer struct { + run func(*exec.Cmd) error + wait func(context.Context, time.Duration) error + wireClient *http.Client + repoClient *http.Client + wireEndpoint string + eventLogger *helpers.EventLogger + rootDir string + osReleasePath string + executable string +} + +func newCloudInitializer(a *App) *cloudInitializer { + transport := common.NewBaseTransport(common.HTTPTransportOptions{ + DialTimeout: 10 * time.Second, + TLSHandshakeTimeout: 10 * time.Second, + ResponseHeaderTimeout: 30 * time.Second, + }) + repoTransport := transport.Clone() + repoTransport.Proxy = http.ProxyFromEnvironment + return &cloudInitializer{ + run: a.cmdRun, + wait: waitCloudRetry, + wireEndpoint: wireServerEndpoint, + wireClient: &http.Client{ + Transport: transport, + Timeout: 30 * time.Second, + // WireServer responses must not redirect to another endpoint. + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + }, + repoClient: &http.Client{Transport: repoTransport, Timeout: 30 * time.Second}, + eventLogger: a.eventLogger, + osReleasePath: a.osReleasePath, + } +} + +func (c *cloudInitializer) close() { + c.wireClient.CloseIdleConnections() + c.repoClient.CloseIdleConnections() +} + +func (c *cloudInitializer) platform() (cloudPlatform, error) { + path := c.osReleasePath + if path == "" { + path = c.path(config.OSReleasePath) + } + data, err := os.ReadFile(path) + if err != nil { + return cloudPlatform{}, fmt.Errorf("read cloud initialization OS release: %w", err) + } + values := config.ParseOSRelease(data) + id := strings.ToLower(values["ID"]) + switch { + case strings.Contains(values["NAME"], "Ubuntu"), id == config.OSReleaseIDUbuntu: + id = config.OSReleaseIDUbuntu + case strings.Contains(id, config.OSReleaseIDFlatcar): + id = config.OSReleaseIDFlatcar + case id == config.OSReleaseIDAzureContainerLinux, + id == config.OSReleaseIDAzureLinux && strings.ToLower(values["VARIANT_ID"]) == config.OSReleaseIDAzureContainerLinux: + id = config.OSReleaseIDAzureContainerLinux + case strings.Contains(values["NAME"], "Microsoft Azure Linux"), id == config.OSReleaseIDAzureLinux: + id = config.OSReleaseIDAzureLinux + default: + return cloudPlatform{}, fmt.Errorf("unsupported cloud initialization OS %q", id) + } + return cloudPlatform{ID: id, Version: values["VERSION_ID"], Codename: values["VERSION_CODENAME"]}, nil +} + +func (c *cloudInitializer) path(path string) string { + if c.rootDir == "" { + return path + } + return filepath.Join(c.rootDir, strings.TrimPrefix(path, "/")) +} + +func (c *cloudInitializer) writeFile(path string, data []byte) error { + return writeCloudFile(c.path(path), data) +} + +func writeCloudFile(path string, data []byte) error { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + root, err := os.OpenRoot(filepath.Dir(path)) + if err != nil { + return err + } + defer root.Close() + // #nosec G306 -- Public CAs, package keys, and repository metadata must be readable by unprivileged clients. + return root.WriteFile(filepath.Base(path), data, 0o644) +} + +func (c *cloudInitializer) withEvent(task string, action func() error) error { + start := time.Now() + err := action() + level, message := helpers.EventLevelInformational, "Completed" + if err != nil { + level, message = helpers.EventLevelError, err.Error() + slog.Error("Azure cloud operation failed", "task", task, "error", err) + } + if c.eventLogger != nil { + c.eventLogger.LogEvent(task, message, level, start, time.Now()) + } + return err +} + +func (c *cloudInitializer) command(ctx context.Context, input []byte, name string, args ...string) ([]byte, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + ctx, cancel := context.WithTimeout(ctx, cloudCommandTimeout) + defer cancel() + cmd := exec.CommandContext(ctx, name, args...) + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Cancel = func() error { + err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + if errors.Is(err, syscall.ESRCH) { + return os.ErrProcessDone + } + return err + } + // A descendant can leave the process group but still hold an output pipe open. + cmd.WaitDelay = cloudCommandWaitDelay + cmd.Env = append(os.Environ(), "LC_ALL=C") + cmd.Stdin = bytes.NewReader(input) + var stdout, stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = &stdout, &stderr + run := c.run + if run == nil { + run = cmdRunner + } + if err := run(cmd); err != nil { + return stdout.Bytes(), fmt.Errorf("%s: %w: %s", name, err, strings.TrimSpace(stderr.String())) + } + if name == "dnf" { + // DNF can report unavailable repositories on stderr despite exiting zero. + _, _ = stdout.Write(stderr.Bytes()) + } + return stdout.Bytes(), nil +} + +func waitCloudRetry(ctx context.Context, delay time.Duration) error { + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + return nil + } +} + +func readCloudResponse(resp *http.Response) ([]byte, error) { + defer resp.Body.Close() + body, err := io.ReadAll(io.LimitReader(resp.Body, cloudResponseLimit+1)) + if err != nil { + return nil, err + } + if len(body) > cloudResponseLimit { + return nil, errors.New("cloud response exceeds size limit") + } + return body, nil +} diff --git a/aks-node-controller/cloud_runtime_events_test.go b/aks-node-controller/cloud_runtime_events_test.go new file mode 100644 index 00000000000..a85583a5010 --- /dev/null +++ b/aks-node-controller/cloud_runtime_events_test.go @@ -0,0 +1,27 @@ +package main + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestCloudRuntimeOperationEvents(t *testing.T) { + for _, tc := range []struct { + name string + err error + }{ + {"completed", nil}, + {"failed", errors.New("operation failed")}, + } { + t.Run(tc.name, func(t *testing.T) { + c := newTestCloudInitializer(t, cloudTestUbuntu) + err := c.withEvent("CloudRuntimeProbe", func() error { return tc.err }) + require.ErrorIs(t, err, tc.err) + events := c.eventLogger.Events() + require.Len(t, events, 1) + require.Equal(t, "AKS.AKSNodeController.CloudRuntimeProbe", events[0].TaskName) + }) + } +} diff --git a/aks-node-controller/cloud_runtime_test.go b/aks-node-controller/cloud_runtime_test.go new file mode 100644 index 00000000000..ed562cffac8 --- /dev/null +++ b/aks-node-controller/cloud_runtime_test.go @@ -0,0 +1,237 @@ +package main + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/Azure/agentbaker/aks-node-controller/config" +) + +func TestCloudFileWrites(t *testing.T) { + t.Run("create and replace", func(t *testing.T) { + path := filepath.Join(t.TempDir(), "certificates", "root.crt") + require.NoError(t, writeCloudFile(path, []byte("original"))) + require.NoError(t, writeCloudFile(path, []byte("replacement"))) + data, err := os.ReadFile(path) + require.NoError(t, err) + require.Equal(t, "replacement", string(data)) + }) + t.Run("reject symlinks outside the destination directory", func(t *testing.T) { + directory := t.TempDir() + outside := filepath.Join(t.TempDir(), "outside.crt") + require.NoError(t, os.WriteFile(outside, []byte("original"), 0o600)) + path := filepath.Join(directory, "root.crt") + require.NoError(t, os.Symlink(outside, path)) + require.Error(t, writeCloudFile(path, []byte("replacement"))) + data, err := os.ReadFile(outside) + require.NoError(t, err) + require.Equal(t, "original", string(data)) + }) +} + +func TestCloudPlatform(t *testing.T) { + for _, tc := range []struct { + name, release, want string + }{ + {"Ubuntu", cloudTestUbuntu, config.OSReleaseIDUbuntu}, + {"AzureLinux", "ID=azurelinux\nNAME=\"Microsoft Azure Linux\"\nVERSION_ID=3.0\n", config.OSReleaseIDAzureLinux}, + {"OSGuard", "ID=azurelinux\nVARIANT_ID=osguard\nVERSION_ID=3.0\n", config.OSReleaseIDAzureLinux}, + {"Flatcar", "ID=flatcar\n", config.OSReleaseIDFlatcar}, + {"ACL", "ID=azurecontainerlinux\n", config.OSReleaseIDAzureContainerLinux}, + {"ACL variant", "ID=azurelinux\nVARIANT_ID=azurecontainerlinux\n", config.OSReleaseIDAzureContainerLinux}, + {"Mixed-case ACL variant", "ID=azurelinux\nVARIANT_ID=AzureContainerLinux\n", config.OSReleaseIDAzureContainerLinux}, + {"unsupported legacy Mariner", "ID=mariner\nNAME=CBL-Mariner\nVERSION_ID=2.0\n", ""}, + {"unsupported", "ID=debian\n", ""}, + {"missing ID", "", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + c := newTestCloudInitializer(t, tc.release) + platform, err := c.platform() + if tc.want == "" { + require.Error(t, err) + } else { + require.NoError(t, err) + require.Equal(t, tc.want, platform.ID) + } + }) + } +} + +func TestCloudCertificateResponseLimits(t *testing.T) { + _, err := readCloudResponse(&http.Response{ + Body: io.NopCloser(strings.NewReader(strings.Repeat("x", cloudResponseLimit+1))), + }) + require.ErrorContains(t, err, "size limit") +} + +func TestCloudCommandSuccess(t *testing.T) { + executable, err := os.Executable() + require.NoError(t, err) + c := &cloudInitializer{} + output, err := c.command(t.Context(), []byte("input"), executable, + "-test.run=^TestCloudCommandHelperProcess$", "--", "echo", "") + require.NoError(t, err) + require.Equal(t, "C:input", string(output)) +} + +func TestCloudCommandAlreadyCanceled(t *testing.T) { + executable, err := os.Executable() + require.NoError(t, err) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + called := false + c := &cloudInitializer{run: func(cmd *exec.Cmd) error { + called = true + return cmd.Run() + }} + output, err := c.command(ctx, nil, executable, + "-test.run=^TestCloudCommandHelperProcess$", "--", "echo", "") + require.ErrorIs(t, err, context.Canceled) + require.False(t, called, "an already-canceled context must not invoke the command runner") + require.Nil(t, output) +} + +func TestCloudCommandCancellation(t *testing.T) { + executable, err := os.Executable() + require.NoError(t, err) + for _, tc := range []struct { + name string + mode string + returnWithin time.Duration + }{ + {"kills descendants with inherited output", "group", 2 * time.Second}, + {"bounds output draining after a descendant leaves the group", "detached", 7 * time.Second}, + } { + t.Run(tc.name, func(t *testing.T) { + readyPath := filepath.Join(t.TempDir(), "child.pid") + ctx, cancel := context.WithCancel(t.Context()) + started := make(chan *os.Process, 1) + finished := make(chan struct{}) + c := &cloudInitializer{run: func(cmd *exec.Cmd) error { + if err := cmd.Start(); err != nil { + return err + } + started <- cmd.Process + return cmd.Wait() + }} + var parent, child *os.Process + t.Cleanup(func() { + cleanupCloudCommand(t, cancel, finished, parent, child) + }) + var output []byte + var commandErr error + go func() { + defer close(finished) + output, commandErr = c.command(ctx, nil, executable, + "-test.run=^TestCloudCommandHelperProcess$", "--", tc.mode, readyPath) + }() + select { + case parent = <-started: + case <-finished: + t.Fatalf("command exited before starting its child: %v", commandErr) + case <-time.After(5 * time.Second): + t.Fatal("command did not start") + } + var childPID int + require.Eventually(t, func() bool { + data, err := os.ReadFile(readyPath) + if err != nil { + return false + } + childPID, err = strconv.Atoi(strings.TrimSpace(string(data))) + return err == nil && childPID > 0 + }, 5*time.Second, 10*time.Millisecond, "command did not start its output-holding child") + var err error + child, err = os.FindProcess(childPID) + require.NoError(t, err) + + cancel() + select { + case <-finished: + require.Error(t, commandErr) + require.Contains(t, string(output), "stdout-marker") + require.ErrorContains(t, commandErr, "stderr-marker") + case <-time.After(tc.returnWithin): + t.Fatalf("command did not return within %s of cancellation", tc.returnWithin) + } + }) + } +} + +func cleanupCloudCommand(t *testing.T, cancel context.CancelFunc, finished <-chan struct{}, parent, child *os.Process) { + t.Helper() + cancel() + killCloudCommandTestProcess(t, child) + killCloudCommandTestProcess(t, parent) + select { + case <-finished: + case <-time.After(5 * time.Second): + t.Error("command did not finish after subprocess cleanup") + } + if child != nil { + if err := child.Release(); err != nil { + t.Errorf("release child process: %v", err) + } + } +} + +func killCloudCommandTestProcess(t *testing.T, process *os.Process) { + t.Helper() + if process == nil { + return + } + if err := process.Kill(); err != nil && + !errors.Is(err, os.ErrProcessDone) && !errors.Is(err, syscall.ESRCH) { + t.Errorf("clean up process %d: %v", process.Pid, err) + } +} + +func TestCloudCommandHelperProcess(t *testing.T) { + if len(os.Args) != 5 || os.Args[2] != "--" { + return + } + runCloudCommandHelperProcess(t) + os.Exit(0) +} + +func runCloudCommandHelperProcess(t *testing.T) { + t.Helper() + switch os.Args[3] { + case "echo": + input, err := io.ReadAll(os.Stdin) + require.NoError(t, err) + _, err = fmt.Fprintf(os.Stdout, "%s:%s", os.Getenv("LC_ALL"), input) + require.NoError(t, err) + case "hold": + time.Sleep(time.Minute) + case "group", "detached": + executable, err := os.Executable() + require.NoError(t, err) + child := exec.Command(executable, os.Args[1], "--", "hold", os.Args[4]) + child.Stdout, child.Stderr = os.Stdout, os.Stderr + if os.Args[3] == "detached" { + child.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + } + require.NoError(t, child.Start()) + defer killCloudCommandTestProcess(t, child.Process) + fmt.Fprintln(os.Stdout, "stdout-marker") + fmt.Fprintln(os.Stderr, "stderr-marker") + require.NoError(t, os.WriteFile(os.Args[4], []byte(strconv.Itoa(child.Process.Pid)), 0o600)) + require.NoError(t, child.Wait()) + default: + t.Fatalf("unknown command helper mode %q", os.Args[3]) + } +} diff --git a/aks-node-controller/cloud_test_helpers_test.go b/aks-node-controller/cloud_test_helpers_test.go new file mode 100644 index 00000000000..849c046a778 --- /dev/null +++ b/aks-node-controller/cloud_test_helpers_test.go @@ -0,0 +1,127 @@ +package main + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/json" + "encoding/pem" + "io" + "math/big" + "net/http" + "net/http/httptest" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Azure/agentbaker/aks-node-controller/config" + "github.com/Azure/agentbaker/aks-node-controller/helpers" + "github.com/stretchr/testify/require" +) + +const cloudTestUbuntu = "ID=ubuntu\nNAME=Ubuntu\nVERSION_ID=22.04\nVERSION_CODENAME=jammy\n" + +func newTestCloudInitializer(t *testing.T, release string) *cloudInitializer { + t.Helper() + c := newCloudInitializer(&App{ + cmdRun: func(cmd *exec.Cmd) error { + if filepath.Base(cmd.Path) == "gpg" { + _, _ = io.WriteString(cmd.Stdout, "dearmored-key") + } + return nil + }, + eventLogger: helpers.NewEventLogger(t.TempDir()), + }) + c.rootDir = t.TempDir() + c.executable = vhdBinaryPath + c.wait = func(ctx context.Context, _ time.Duration) error { return ctx.Err() } + require.NoError(t, c.writeFile(config.OSReleasePath, []byte(release))) + require.NoError(t, c.writeFile("/etc/ssl/certs/ca-certificates.crt", []byte("system-ca-bundle"))) + t.Cleanup(c.close) + return c +} + +func cloudTestCertificate(t *testing.T) []byte { + t.Helper() + public, private, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + template := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: "ANC cloud initialization test CA"}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + IsCA: true, + BasicConstraintsValid: true, + KeyUsage: x509.KeyUsageCertSign, + } + der, err := x509.CreateCertificate(rand.Reader, template, template, public, private) + require.NoError(t, err) + return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) +} + +func serveCloudTestResponses(t *testing.T, c *cloudInitializer, cert []byte, optIn string) <-chan string { + t.Helper() + requests := make(chan string, 100) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests <- r.URL.Path + "?" + r.URL.RawQuery + switch kind := r.URL.Query().Get("type"); { + case r.URL.Path == "/acms/isOptedInForRootCerts": + _, _ = io.WriteString(w, optIn) + case kind == "cacertificates": + _ = json.NewEncoder(w).Encode(map[string]any{"Certificates": []map[string]string{ + {"Name": "root.cer", "CertBody": strings.ReplaceAll(string(cert), "\n", "\r\n")}, + }}) + case kind == "operationrequestsroot", kind == "operationrequestsintermediate": + name := "root.crt" + if kind == "operationrequestsintermediate" { + name = "intermediate.crt" + } + _ = json.NewEncoder(w).Encode(map[string]any{"OperationsInfo": []map[string]string{{"ResouceFileName": name}}}) + case kind == "root", kind == "intermediate": + _, _ = w.Write(cert) + case strings.HasPrefix(r.URL.Path, "/keys/"): + _, _ = io.WriteString(w, "armored-public-package-key") + case strings.HasPrefix(r.URL.Path, "/microsoft/ubuntu/"): + _, _ = io.WriteString(w, "repository available") + default: + t.Errorf("unexpected cloud request: %s", r.URL) + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(server.Close) + c.wireEndpoint = server.URL + c.wireClient, c.repoClient = server.Client(), server.Client() + return requests +} + +func serveCloudOperationTestResponses(t *testing.T, c *cloudInitializer, roots, intermediates []string) { + t.Helper() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch kind := r.URL.Query().Get("type"); { + case r.URL.Path == "/acms/isOptedInForRootCerts": + _, _ = io.WriteString(w, `{"IsOptedInForRootCerts":true}`) + case kind == "operationrequestsroot", kind == "operationrequestsintermediate": + names := roots + if kind == "operationrequestsintermediate" { + names = intermediates + } + operations := make([]map[string]string, 0, len(names)) + for _, name := range names { + operations = append(operations, map[string]string{"ResouceFileName": name}) + } + _ = json.NewEncoder(w).Encode(map[string]any{"OperationsInfo": operations}) + case kind == "missing": + w.WriteHeader(http.StatusServiceUnavailable) + case kind == "empty": + _, _ = io.WriteString(w, "\n\n") + default: + _, _ = io.WriteString(w, "certificate payload\n\n") + } + })) + t.Cleanup(server.Close) + c.wireEndpoint = server.URL +} diff --git a/e2e/scenario/validators.go b/e2e/scenario/validators.go index 2b3ab220bee..f011e8fef13 100644 --- a/e2e/scenario/validators.go +++ b/e2e/scenario/validators.go @@ -962,6 +962,24 @@ func ValidateFileHasContent(ctx context.Context, s *Scenario, fileName string, c return fmt.Errorf("expected file %s to have contents %q, but it does not. It had contents %s", fileName, contents, actualContents) } +// validateFileHasAnyContent passes the test if the specified file contains at least one of the specified contents. +func validateFileHasAnyContent(ctx context.Context, s *Scenario, fileName string, contents ...string) error { + for _, content := range contents { + hasContent, err := fileHasContent(ctx, s, fileName, content) + if err != nil { + return fmt.Errorf("check whether file %s has contents %q: %w", fileName, content, err) + } + if hasContent { + return nil + } + } + actualContents, err := getFileContent(ctx, s, fileName) + if err != nil { + return fmt.Errorf("expected file %s to have any of contents %q. Could not determine actual contents due to %w", fileName, contents, err) + } + return fmt.Errorf("expected file %s to have any of contents %q, but it does not. It had contents %s", fileName, contents, actualContents) +} + func ValidateKubeletEventBurst(ctx context.Context, s *Scenario, expected int32) error { content, err := getFileContent(ctx, s, "/etc/default/kubeletconfig.json") if err != nil { @@ -5111,15 +5129,20 @@ func validateDRAMIGAllocation(claim *resourcev1.ResourceClaim, resourceSlices *r // ValidateRCV1PCertMode validates that the rcv1p certificate endpoint mode was used during // Linux node provisioning, certificates were downloaded and installed, and a refresh task was scheduled. +// Nodes initialize the cloud with either init-aks-cloud.sh or aks-node-controller's native +// implementation, which log and schedule refresh differently, so the checks accept either one. func ValidateRCV1PCertMode(ctx context.Context, s *Scenario) error { var errs []error errs = append(errs, // Validate the provisioning log shows rcv1p mode was selected - ValidateFileHasContent(ctx, s, "/var/log/azure/cluster-provision.log", - "Using custom cloud certificate endpoint mode: rcv1p"), - // Validate the subscription is opted in for root certs - ValidateFileHasContent(ctx, s, "/var/log/azure/cluster-provision.log", - "IsOptedInForRootCerts=true"), + validateFileHasAnyContent(ctx, s, "/var/log/azure/cluster-provision.log", + "Using custom cloud certificate endpoint mode: rcv1p", + `selecting Azure cloud certificate endpoint","legacy":false`), + // Validate the subscription is opted in for root certs. + // aks-node-controller installs rcv1p certificates only after wireserver reports the opt-in. + validateFileHasAnyContent(ctx, s, "/var/log/azure/cluster-provision.log", + "IsOptedInForRootCerts=true", + "installed Azure cloud CA certificates"), // Validate certificates were downloaded ValidateNonEmptyDirectory(ctx, s, "/root/AzureCACertificates"), ) @@ -5142,15 +5165,18 @@ func ValidateRCV1PCertMode(ctx context.Context, s *Scenario) error { } } else { // Ubuntu, Mariner, AzureLinux use cron - if _, err := execScriptOnVMForScenarioValidateExitCode(ctx, s, - "sudo crontab -l 2>/dev/null | grep -q ca-refresh", - 0, "expected ca-refresh cron entry"); err != nil { - errs = append(errs, fmt.Errorf("check ca-refresh cron entry: %w", err)) + if _, err := execScriptOnVMForScenarioValidateExitCode(ctx, s, rcv1pRefreshCronCheck, + 0, "expected certificate refresh cron entry"); err != nil { + errs = append(errs, fmt.Errorf("check certificate refresh cron entry: %w", err)) } } return errors.Join(errs...) } +// rcv1pRefreshCronCheck succeeds when root's crontab has the certificate refresh entry of +// init-aks-cloud.sh (ca-refresh) or aks-node-controller (refresh-cloud-certificates). +const rcv1pRefreshCronCheck = "sudo crontab -l 2>/dev/null | grep -qE 'ca-refresh|refresh-cloud-certificates'" + // rcv1pTrustStoreDir returns the OS trust store directory for the given scenario's distro. func rcv1pTrustStoreDir(s *Scenario) string { switch s.VHD.OS { @@ -5207,15 +5233,18 @@ func ValidateRCV1PCertModeWindows(ctx context.Context, s *Scenario) error { // ValidateRCV1PNotOptedIn validates that when the VM does NOT have the opt-in tag, // wireserver returns IsOptedInForRootCerts=false and no certificates are installed, // even in the RCV1P subscription with PlatformSettingsOverride registered. +// Like ValidateRCV1PCertMode, the checks accept init-aks-cloud.sh or aks-node-controller output. func ValidateRCV1PNotOptedIn(ctx context.Context, s *Scenario) error { var errs []error errs = append(errs, // Validate the provisioning log shows rcv1p mode was selected - ValidateFileHasContent(ctx, s, "/var/log/azure/cluster-provision.log", - "Using custom cloud certificate endpoint mode: rcv1p"), + validateFileHasAnyContent(ctx, s, "/var/log/azure/cluster-provision.log", + "Using custom cloud certificate endpoint mode: rcv1p", + `selecting Azure cloud certificate endpoint","legacy":false`), // Validate wireserver reported not opted in - ValidateFileHasContent(ctx, s, "/var/log/azure/cluster-provision.log", - "Skipping custom cloud root cert installation because IsOptedInForRootCerts is not true"), + validateFileHasAnyContent(ctx, s, "/var/log/azure/cluster-provision.log", + "Skipping custom cloud root cert installation because IsOptedInForRootCerts is not true", + "Azure cloud root certificates are not opted in, skipping certificate installation"), // Validate no certificates were downloaded ValidateEmptyDirectory(ctx, s, "/root/AzureCACertificates"), ) @@ -5230,10 +5259,9 @@ func ValidateRCV1PNotOptedIn(ctx context.Context, s *Scenario) error { } } else { // Ubuntu, Mariner, AzureLinux use cron. - if _, err := execScriptOnVMForScenarioValidateExitCode(ctx, s, - "sudo crontab -l 2>/dev/null | grep -q ca-refresh", - 1, "expected no ca-refresh cron entry when not opted in"); err != nil { - errs = append(errs, fmt.Errorf("check that no ca-refresh cron entry exists: %w", err)) + if _, err := execScriptOnVMForScenarioValidateExitCode(ctx, s, rcv1pRefreshCronCheck, + 1, "expected no certificate refresh cron entry when not opted in"); err != nil { + errs = append(errs, fmt.Errorf("check that no certificate refresh cron entry exists: %w", err)) } } return errors.Join(errs...)