-
Notifications
You must be signed in to change notification settings - Fork 84
feat(control-plane): replace TokenReview with RSA keypair auth for runner token endpoint #1216
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
134 changes: 134 additions & 0 deletions
134
components/ambient-control-plane/internal/keypair/bootstrap.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| package keypair | ||
|
|
||
| import ( | ||
| "context" | ||
| "crypto/rand" | ||
| "crypto/rsa" | ||
| "crypto/x509" | ||
| "encoding/base64" | ||
| "encoding/pem" | ||
| "fmt" | ||
|
|
||
| "github.com/ambient-code/platform/components/ambient-control-plane/internal/kubeclient" | ||
| "github.com/rs/zerolog" | ||
| k8serrors "k8s.io/apimachinery/pkg/api/errors" | ||
| "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" | ||
| ) | ||
|
|
||
| const ( | ||
| SecretName = "ambient-cp-token-keypair" | ||
| privateKeyKey = "private.pem" | ||
| publicKeyKey = "public.pem" | ||
| rsaKeyBits = 4096 | ||
| ) | ||
|
|
||
| type KeyPair struct { | ||
| PrivateKeyPEM []byte | ||
| PublicKeyPEM []byte | ||
| } | ||
|
|
||
| func EnsureKeypairSecret(ctx context.Context, kube *kubeclient.KubeClient, namespace string, logger zerolog.Logger) (*KeyPair, error) { | ||
| existing, err := kube.GetSecret(ctx, namespace, SecretName) | ||
| if err == nil { | ||
| return keypairFromSecret(existing) | ||
| } | ||
| if !k8serrors.IsNotFound(err) { | ||
| return nil, fmt.Errorf("checking for keypair secret: %w", err) | ||
| } | ||
|
|
||
| logger.Info().Str("namespace", namespace).Str("secret", SecretName).Msg("keypair secret not found, generating new RSA keypair") | ||
|
|
||
| kp, err := generateKeypair() | ||
| if err != nil { | ||
| return nil, fmt.Errorf("generating RSA keypair: %w", err) | ||
| } | ||
|
|
||
| secret := &unstructured.Unstructured{ | ||
| Object: map[string]interface{}{ | ||
| "apiVersion": "v1", | ||
| "kind": "Secret", | ||
| "metadata": map[string]interface{}{ | ||
| "name": SecretName, | ||
| "namespace": namespace, | ||
| "labels": map[string]interface{}{ | ||
| "app": "ambient-control-plane", | ||
| "ambient-code.io/managed-by": "ambient-control-plane", | ||
| }, | ||
| }, | ||
| "type": "Opaque", | ||
| "data": map[string]interface{}{ | ||
| privateKeyKey: base64.StdEncoding.EncodeToString(kp.PrivateKeyPEM), | ||
| publicKeyKey: base64.StdEncoding.EncodeToString(kp.PublicKeyPEM), | ||
| }, | ||
| }, | ||
| } | ||
|
|
||
| if _, createErr := kube.CreateSecret(ctx, secret); createErr != nil { | ||
| if !k8serrors.IsAlreadyExists(createErr) { | ||
| return nil, fmt.Errorf("creating keypair secret: %w", createErr) | ||
| } | ||
| existing, err = kube.GetSecret(ctx, namespace, SecretName) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("re-reading keypair secret after race: %w", err) | ||
| } | ||
| return keypairFromSecret(existing) | ||
| } | ||
|
|
||
| logger.Info().Str("namespace", namespace).Str("secret", SecretName).Msg("RSA keypair secret created") | ||
| return kp, nil | ||
| } | ||
|
|
||
| func keypairFromSecret(secret *unstructured.Unstructured) (*KeyPair, error) { | ||
| data, _, _ := unstructured.NestedMap(secret.Object, "data") | ||
|
|
||
| privB64, ok := data[privateKeyKey].(string) | ||
| if !ok || privB64 == "" { | ||
| return nil, fmt.Errorf("keypair secret missing %q key", privateKeyKey) | ||
| } | ||
| pubB64, ok := data[publicKeyKey].(string) | ||
| if !ok || pubB64 == "" { | ||
| return nil, fmt.Errorf("keypair secret missing %q key", publicKeyKey) | ||
| } | ||
|
|
||
| privPEM, err := base64.StdEncoding.DecodeString(privB64) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("decoding private key from secret: %w", err) | ||
| } | ||
| pubPEM, err := base64.StdEncoding.DecodeString(pubB64) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("decoding public key from secret: %w", err) | ||
| } | ||
|
|
||
| return &KeyPair{PrivateKeyPEM: privPEM, PublicKeyPEM: pubPEM}, nil | ||
| } | ||
|
|
||
| func generateKeypair() (*KeyPair, error) { | ||
| privKey, err := rsa.GenerateKey(rand.Reader, rsaKeyBits) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("generating RSA key: %w", err) | ||
| } | ||
|
|
||
| privPEM := pem.EncodeToMemory(&pem.Block{ | ||
| Type: "RSA PRIVATE KEY", | ||
| Bytes: x509.MarshalPKCS1PrivateKey(privKey), | ||
| }) | ||
|
|
||
| pubDER, err := x509.MarshalPKIXPublicKey(&privKey.PublicKey) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("marshaling public key: %w", err) | ||
| } | ||
| pubPEM := pem.EncodeToMemory(&pem.Block{ | ||
| Type: "PUBLIC KEY", | ||
| Bytes: pubDER, | ||
| }) | ||
|
|
||
| return &KeyPair{PrivateKeyPEM: privPEM, PublicKeyPEM: pubPEM}, nil | ||
| } | ||
|
|
||
| func ParsePrivateKey(pemBytes []byte) (*rsa.PrivateKey, error) { | ||
| block, _ := pem.Decode(pemBytes) | ||
| if block == nil { | ||
| return nil, fmt.Errorf("failed to decode PEM block for private key") | ||
| } | ||
| return x509.ParsePKCS1PrivateKey(block.Bytes) | ||
| } | ||
160 changes: 160 additions & 0 deletions
160
components/ambient-control-plane/internal/keypair/bootstrap_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,160 @@ | ||
| package keypair | ||
|
|
||
| import ( | ||
| "context" | ||
| "crypto/rsa" | ||
| "encoding/base64" | ||
| "testing" | ||
|
|
||
| "github.com/rs/zerolog" | ||
| "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" | ||
| "k8s.io/apimachinery/pkg/runtime" | ||
| "k8s.io/client-go/dynamic/fake" | ||
|
|
||
| "github.com/ambient-code/platform/components/ambient-control-plane/internal/kubeclient" | ||
| ) | ||
|
|
||
| func newFakeKubeClient(objects ...runtime.Object) *kubeclient.KubeClient { | ||
| scheme := runtime.NewScheme() | ||
| dynClient := fake.NewSimpleDynamicClient(scheme, objects...) | ||
| return kubeclient.NewFromDynamic(dynClient, zerolog.Nop()) | ||
| } | ||
|
|
||
| func TestGenerateKeypair(t *testing.T) { | ||
| kp, err := generateKeypair() | ||
| if err != nil { | ||
| t.Fatalf("generateKeypair() error: %v", err) | ||
| } | ||
| if len(kp.PrivateKeyPEM) == 0 { | ||
| t.Error("PrivateKeyPEM is empty") | ||
| } | ||
| if len(kp.PublicKeyPEM) == 0 { | ||
| t.Error("PublicKeyPEM is empty") | ||
| } | ||
| } | ||
|
|
||
| func TestParsePrivateKey(t *testing.T) { | ||
| kp, err := generateKeypair() | ||
| if err != nil { | ||
| t.Fatalf("generateKeypair() error: %v", err) | ||
| } | ||
| privKey, err := ParsePrivateKey(kp.PrivateKeyPEM) | ||
| if err != nil { | ||
| t.Fatalf("ParsePrivateKey() error: %v", err) | ||
| } | ||
| if privKey == nil { | ||
| t.Fatal("ParsePrivateKey() returned nil") | ||
| } | ||
| if _, ok := interface{}(privKey).(*rsa.PrivateKey); !ok { | ||
| t.Error("parsed key is not *rsa.PrivateKey") | ||
| } | ||
| } | ||
|
|
||
| func TestParsePrivateKey_InvalidPEM(t *testing.T) { | ||
| _, err := ParsePrivateKey([]byte("not a pem block")) | ||
| if err == nil { | ||
| t.Error("expected error for invalid PEM, got nil") | ||
| } | ||
| } | ||
|
|
||
| func TestKeypairFromSecret_MissingPrivateKey(t *testing.T) { | ||
| secret := &unstructured.Unstructured{ | ||
| Object: map[string]interface{}{ | ||
| "apiVersion": "v1", | ||
| "kind": "Secret", | ||
| "metadata": map[string]interface{}{"name": SecretName, "namespace": "test"}, | ||
| "data": map[string]interface{}{ | ||
| publicKeyKey: base64.StdEncoding.EncodeToString([]byte("pub")), | ||
| }, | ||
| }, | ||
| } | ||
| _, err := keypairFromSecret(secret) | ||
| if err == nil { | ||
| t.Error("expected error for missing private key, got nil") | ||
| } | ||
| } | ||
|
|
||
| func TestKeypairFromSecret_MissingPublicKey(t *testing.T) { | ||
| secret := &unstructured.Unstructured{ | ||
| Object: map[string]interface{}{ | ||
| "apiVersion": "v1", | ||
| "kind": "Secret", | ||
| "metadata": map[string]interface{}{"name": SecretName, "namespace": "test"}, | ||
| "data": map[string]interface{}{ | ||
| privateKeyKey: base64.StdEncoding.EncodeToString([]byte("priv")), | ||
| }, | ||
| }, | ||
| } | ||
| _, err := keypairFromSecret(secret) | ||
| if err == nil { | ||
| t.Error("expected error for missing public key, got nil") | ||
| } | ||
| } | ||
|
|
||
| func TestKeypairFromSecret_ValidSecret(t *testing.T) { | ||
| kp, err := generateKeypair() | ||
| if err != nil { | ||
| t.Fatalf("generateKeypair() error: %v", err) | ||
| } | ||
| secret := &unstructured.Unstructured{ | ||
| Object: map[string]interface{}{ | ||
| "apiVersion": "v1", | ||
| "kind": "Secret", | ||
| "metadata": map[string]interface{}{"name": SecretName, "namespace": "test"}, | ||
| "data": map[string]interface{}{ | ||
| privateKeyKey: base64.StdEncoding.EncodeToString(kp.PrivateKeyPEM), | ||
| publicKeyKey: base64.StdEncoding.EncodeToString(kp.PublicKeyPEM), | ||
| }, | ||
| }, | ||
| } | ||
| got, err := keypairFromSecret(secret) | ||
| if err != nil { | ||
| t.Fatalf("keypairFromSecret() error: %v", err) | ||
| } | ||
| if string(got.PrivateKeyPEM) != string(kp.PrivateKeyPEM) { | ||
| t.Error("PrivateKeyPEM mismatch") | ||
| } | ||
| if string(got.PublicKeyPEM) != string(kp.PublicKeyPEM) { | ||
| t.Error("PublicKeyPEM mismatch") | ||
| } | ||
| } | ||
|
|
||
| func TestEnsureKeypairSecret_CreatesWhenMissing(t *testing.T) { | ||
| kube := newFakeKubeClient() | ||
| ctx := context.Background() | ||
|
|
||
| kp, err := EnsureKeypairSecret(ctx, kube, "test-ns", zerolog.Nop()) | ||
| if err != nil { | ||
| t.Fatalf("EnsureKeypairSecret() error: %v", err) | ||
| } | ||
| if len(kp.PrivateKeyPEM) == 0 || len(kp.PublicKeyPEM) == 0 { | ||
| t.Error("returned keypair has empty PEM fields") | ||
| } | ||
|
|
||
| privKey, err := ParsePrivateKey(kp.PrivateKeyPEM) | ||
| if err != nil { | ||
| t.Fatalf("generated private key is not parseable: %v", err) | ||
| } | ||
| if privKey.N.BitLen() != rsaKeyBits { | ||
| t.Errorf("key size: got %d, want %d", privKey.N.BitLen(), rsaKeyBits) | ||
| } | ||
| } | ||
|
|
||
| func TestEnsureKeypairSecret_ReturnsExistingWhenPresent(t *testing.T) { | ||
| ctx := context.Background() | ||
| kube := newFakeKubeClient() | ||
|
|
||
| first, err := EnsureKeypairSecret(ctx, kube, "test-ns", zerolog.Nop()) | ||
| if err != nil { | ||
| t.Fatalf("first call error: %v", err) | ||
| } | ||
|
|
||
| second, err := EnsureKeypairSecret(ctx, kube, "test-ns", zerolog.Nop()) | ||
| if err != nil { | ||
| t.Fatalf("second call error: %v", err) | ||
| } | ||
|
|
||
| if string(first.PrivateKeyPEM) != string(second.PrivateKeyPEM) { | ||
| t.Error("second call returned different private key — should reuse existing Secret") | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Silently ignoring
NestedMaperror may mask corrupted Secret data.If the Secret exists but has a malformed structure, the error is discarded and the code proceeds to fail confusingly on subsequent key lookups.
Proposed fix
func keypairFromSecret(secret *unstructured.Unstructured) (*KeyPair, error) { - data, _, _ := unstructured.NestedMap(secret.Object, "data") + data, found, err := unstructured.NestedMap(secret.Object, "data") + if err != nil || !found { + return nil, fmt.Errorf("keypair secret has invalid or missing data field") + }📝 Committable suggestion
🤖 Prompt for AI Agents