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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 39 additions & 15 deletions aks-node-controller/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
16 changes: 16 additions & 0 deletions aks-node-controller/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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",
Expand Down
128 changes: 128 additions & 0 deletions aks-node-controller/cloud_certificate_store.go
Original file line number Diff line number Diff line change
@@ -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)
}
104 changes: 104 additions & 0 deletions aks-node-controller/cloud_certificate_store_behavior_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
18 changes: 18 additions & 0 deletions aks-node-controller/cloud_certificate_store_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
Loading
Loading