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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,9 @@ to [Semantic Versioning](https://semver.org/).

### Fixed

- An app's secret holds its value, not the value's base64 text. The secret-fetch broker answers `plaintext_b64` and External Secrets' webhook provider writes it as is, so each tenant ExternalSecret now sets `decodingStrategy: Base64` (#108).
- A secret set with `loopscale secret set` reaches the app's process even when the app's configuration declares no secrets. The container mounts the environment's and the app's user-secrets Secrets with `envFrom`, optionally unless the app declares secrets; before, it mounted them only for declared secrets, so the Secret that External Secrets wrote was never read (#108).
- Staging and production install the secret-fetch broker on the cells (`profile.secretFetchBroker`), so tenant secrets are delivered to apps. The cells call loopzero-api through an internal ALB on core that forwards `/internal/v1/secret-fetch` alone (`secretFetchLoadBalancer` in the loopzero-api chart). Production needs `LOOPZERO_CORE_API_INTERNAL_CERTIFICATE_ARN` for its HTTPS listener and `LOOPZERO_CORE_API_INTERNAL_URL` for the cells, and refuses to render without them. `task staging:platform` reads the ALB's address after the core sync and seeds one broker token per cell with `loopzero-ops seed broker`, which now reaches cells through contexts named by `LOOPZERO_CELL_CONTEXT_PREFIX` (#108).
- The Status page queries the Prometheus the API pod reaches (`LOOPZERO_DATA_PLANE_POLLER_PROMETHEUS_URL`) before `LOOPZERO_PROMETHEUS_ADDRESS`, which canary analyses on the cells use; staging names its core Prometheus (#102).
- `POST /projects/{name}/scale` answers 404 `APP_NOT_FOUND`, naming the apps the project has, for an app the active release of the environment does not declare. It used to answer 200 `changed: true` and write a scaling config no workload reads (#97)
- `GET /environments` reports the commit the user deployed as `last_deploy_sha`, the active release's build commit, instead of the commit of the GitOps repository (#101)
Expand Down
31 changes: 31 additions & 0 deletions api/internal/k8s/secretsync/external_secret_decoding_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright 2025-2026 The LoopZero Authors

package secretsync

import (
"testing"

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

"github.com/getloopscale/loopzero/api/internal/ports"
)

// The secret-fetch broker answers {"plaintext_b64": base64(value)}, and External Secrets'
// webhook provider writes what the result jsonPath selects as is. Without the Base64
// decoding strategy the app received the base64 text instead of its secret.
func TestExternalSecretDecodesTheBrokersBase64Answer(t *testing.T) {
ref := ports.SecretRef{TenantID: "tn-a", Project: "shop", Environment: "production", App: "api", Name: "DB_URL"}

es := externalSecretObject(ref, "loopzero-tn-a-shop-production")

data, _, _ := unstructured.NestedSlice(es.Object, "spec", "data")
if len(data) != 1 {
t.Fatalf("spec.data has %d entries, want 1", len(data))
}
entry, _ := data[0].(map[string]interface{})
got, _, _ := unstructured.NestedString(entry, "remoteRef", "decodingStrategy")
if got != "Base64" {
t.Errorf("remoteRef.decodingStrategy = %q, want Base64: the broker's value is base64-encoded", got)
}
}
6 changes: 5 additions & 1 deletion api/internal/k8s/secretsync/secret_k8s_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ func externalSecretObject(ref ports.SecretRef, namespace string) *unstructured.U
// endpoint with a Bearer token; loopzero-api validates the
// auth, enforces tenant↔cell binding (EC-07), decrypts
// the vault:v1: ciphertext via OpenBao transit, and
// returns plaintext_b64. ESO base64-decodes into the
// returns plaintext_b64, which decodingStrategy Base64 below decodes into the
// materialized K8s Secret. LIVE-validated 2026-06-10
// J-22 walkthrough (ClusterSecretStore Ready=True +
// in-cluster probe HTTP 200 + plaintext round-trip).
Expand Down Expand Up @@ -262,6 +262,10 @@ func externalSecretObject(ref ports.SecretRef, namespace string) *unstructured.U
// chi routing.
"key": tenantID,
"property": fmt.Sprintf("%s.%s.%s", name, projectID, env),
// The broker answers plaintext_b64, and the webhook provider
// writes what the result jsonPath selects as is: without this
// the app's Secret held the base64 text, not the value.
"decodingStrategy": "Base64",
},
},
},
Expand Down
20 changes: 15 additions & 5 deletions api/internal/manifests/renderer_rollout.go
Original file line number Diff line number Diff line change
Expand Up @@ -436,11 +436,21 @@ func buildAppContainer(ri renderScope, app AppManifestInput, port int) k8sContai
}
}

if len(app.Secrets) > 0 {
secretRefName := naming.UserSecretName(ri.TenantID, ri.ProjectID, ri.Environment, app.Name)
container.EnvFrom = []k8sEnvFromSource{
{SecretRef: k8sSecretRef{Name: secretRefName}},
}
// The Secrets secret sync writes from `loopscale secret set`: the environment's,
// for a secret set without an app, then the app's, so the app's value wins on a
// shared key. Both are mounted whether or not the app's configuration declares a
// secret, because a secret set for the app is delivered either way; mounting only
// declared ones left every undeclared secret out of the process. An app that
// declares secrets requires its Secret, and the pod waits for it; otherwise both
// are optional, so an app with no secret starts.
optional := true
appSecretOptional := len(app.Secrets) == 0
container.EnvFrom = []k8sEnvFromSource{
{SecretRef: k8sSecretRef{Name: naming.UserSecretName(ri.TenantID, ri.ProjectID, ri.Environment, ""), Optional: &optional}},
{SecretRef: k8sSecretRef{Name: naming.UserSecretName(ri.TenantID, ri.ProjectID, ri.Environment, app.Name)}},
}
if appSecretOptional {
container.EnvFrom[1].SecretRef.Optional = &optional
}

return container
Expand Down
3 changes: 2 additions & 1 deletion api/internal/manifests/renderer_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,8 @@ type k8sEnvFromSource struct {
}

type k8sSecretRef struct {
Name string `json:"name"`
Name string `json:"name"`
Optional *bool `json:"optional,omitempty"`
}

type k8sProbe struct {
Expand Down
46 changes: 43 additions & 3 deletions api/internal/manifests/user_secret_ref_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,19 @@ import (
"github.com/getloopscale/loopzero/pkg/naming"
)

// secretRefOf returns the container's envFrom entry for the Secret named name.
func secretRefOf(c k8sContainer, name string) (k8sSecretRef, bool) {
for _, src := range c.EnvFrom {
if src.SecretRef.Name == name {
return src.SecretRef, true
}
}
return k8sSecretRef{}, false
}

// Secret sync writes the Secret named by naming.UserSecretName; the container
// must mount exactly that name, or the app starts without its secrets.
// must mount exactly that name, or the app starts without its secrets. A secret the
// app declares is required: the pod does not start without it.
func TestAppContainerMountsTheUserSecretSecretSyncWrites(t *testing.T) {
// Arrange
ri := baseInput()
Expand All @@ -21,7 +32,36 @@ func TestAppContainerMountsTheUserSecretSecretSyncWrites(t *testing.T) {

// Assert
want := naming.UserSecretName(ri.TenantID, ri.ProjectID, ri.Environment, app.Name)
if len(c.EnvFrom) != 1 || c.EnvFrom[0].SecretRef.Name != want {
t.Fatalf("envFrom = %+v, want one secretRef %q", c.EnvFrom, want)
ref, ok := secretRefOf(c, want)
if !ok {
t.Fatalf("envFrom = %+v, want a secretRef %q", c.EnvFrom, want)
}
if ref.Optional != nil && *ref.Optional {
t.Errorf("the Secret of an app that declares secrets is optional; want it required")
}
}

// A secret set with `loopscale secret set` reaches the app even when the app's
// configuration declares none: secret sync writes the app's Secret (and the
// environment-wide one for a secret set without an app), and the container mounts
// both, optionally, so an app with no secret still starts.
func TestAppContainerMountsUndeclaredUserSecretsOptionally(t *testing.T) {
// Arrange
ri := baseInput()
app := AppManifestInput{Name: "api", Type: ServiceTypeServer, Port: 8080, ImageRef: "reg/acme:1"}

// Act
c := buildAppContainer(scopeFor(t, ri), app, 8080)

// Assert
envWide := naming.UserSecretName(ri.TenantID, ri.ProjectID, ri.Environment, "")
appWide := naming.UserSecretName(ri.TenantID, ri.ProjectID, ri.Environment, app.Name)
if len(c.EnvFrom) != 2 || c.EnvFrom[0].SecretRef.Name != envWide || c.EnvFrom[1].SecretRef.Name != appWide {
t.Fatalf("envFrom = %+v, want the environment's Secret %q then the app's %q, so the app's value wins", c.EnvFrom, envWide, appWide)
}
for _, src := range c.EnvFrom {
if src.SecretRef.Optional == nil || !*src.SecretRef.Optional {
t.Errorf("secretRef %q is required; an app without secrets would not start", src.SecretRef.Name)
}
}
}
70 changes: 70 additions & 0 deletions charts/loopzero-api/templates/secret-fetch-load-balancer.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
{{- /*
The internal Application Load Balancer the cells' External Secrets reach the
secret-fetch broker through (POST /internal/v1/secret-fetch/{tenant_id}/{secret_name}).
Off by default. The AWS Load Balancer Controller makes the ALB from the Ingress, with
instance targets on the NodePort Service below, as for infra/helm/loki/values-alb.yaml.

The ALB is internal (VPC only) and forwards the secret-fetch prefix alone: every other
path of the API, /internal included, answers the ALB's 404 and never reaches a pod.

The listener is HTTPS 443 with the ACM certificate certificateArn names, because the
broker sends a bearer token. plaintextListener is for an ALB that is reached only
through a TLS hop of its own (staging's AWS emulator, whose HTTPS endpoint proxies to
the ALB); without it and without a certificate the render fails.
*/}}
{{- with .Values.secretFetchLoadBalancer }}
{{- if .enabled }}
{{- if and (not .plaintextListener) (not .certificateArn) }}
{{- fail "loopzero-api: secretFetchLoadBalancer.enabled needs secretFetchLoadBalancer.certificateArn (an ACM certificate for the HTTPS listener): the broker sends a bearer token, and an HTTP listener is allowed only with plaintextListener behind a TLS hop" }}
{{- end }}
{{- $name := printf "%s-secret-fetch" (include "loopzero-common.fullname" $) }}
apiVersion: v1
kind: Service
metadata:
name: {{ $name }}
labels:
{{- include "loopzero-common.labels" $ | nindent 4 }}
app.kubernetes.io/component: secret-fetch-load-balancer
spec:
type: NodePort
selector:
{{- include "loopzero-common.selectorLabels" $ | nindent 4 }}
ports:
- name: http
port: {{ $.Values.service.port }}
targetPort: http
protocol: TCP
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: {{ $name }}
labels:
{{- include "loopzero-common.labels" $ | nindent 4 }}
app.kubernetes.io/component: secret-fetch-load-balancer
annotations:
alb.ingress.kubernetes.io/scheme: internal
alb.ingress.kubernetes.io/target-type: instance
alb.ingress.kubernetes.io/backend-protocol: HTTP
alb.ingress.kubernetes.io/healthcheck-path: /api/v1/health
{{- if .plaintextListener }}
alb.ingress.kubernetes.io/listen-ports: '[{"HTTP": 80}]'
{{- else }}
alb.ingress.kubernetes.io/listen-ports: '[{"HTTPS": 443}]'
alb.ingress.kubernetes.io/certificate-arn: {{ .certificateArn | quote }}
alb.ingress.kubernetes.io/ssl-policy: ELBSecurityPolicy-TLS13-1-2-2021-06
{{- end }}
spec:
ingressClassName: alb
rules:
- http:
paths:
- path: /internal/v1/secret-fetch
pathType: Prefix
backend:
service:
name: {{ $name }}
port:
name: http
{{- end }}
{{- end }}
19 changes: 18 additions & 1 deletion charts/loopzero-api/values.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -612,7 +612,7 @@
},
"interval": {
"type": "string",
"pattern": "^([0-9]+(\\.[0-9]+)?(ns|us|\u00b5s|ms|s|m|h))+$"
"pattern": "^([0-9]+(\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$"
}
}
},
Expand Down Expand Up @@ -830,6 +830,23 @@
"type": "object",
"description": "Values block consumed by the loopzero-common library subchart."
},
"secretFetchLoadBalancer": {
"type": "object",
"additionalProperties": false,
"description": "Internal ALB (AWS Load Balancer Controller Ingress) forwarding only /internal/v1/secret-fetch to the API, for the cells' External Secrets. Off by default. HTTPS with certificateArn unless plaintextListener.",
"properties": {
"enabled": {
"type": "boolean"
},
"certificateArn": {
"type": "string",
"pattern": "^$|^arn:aws[a-z-]*:acm:[a-z0-9-]+:[0-9]{12}:certificate/[A-Za-z0-9-]+$"
},
"plaintextListener": {
"type": "boolean"
}
}
},
"reloader": {
"type": "object",
"additionalProperties": false,
Expand Down
12 changes: 12 additions & 0 deletions charts/loopzero-api/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,18 @@ ingressRoute:
# the host), or CFManaged when TLS terminates at the Cloudflare edge.
certIssuer: CFManaged

# The internal Application Load Balancer the cells' External Secrets reach the
# secret-fetch broker through (templates/secret-fetch-load-balancer.yaml): an Ingress
# for the AWS Load Balancer Controller that forwards /internal/v1/secret-fetch alone. Off:
# a published chart does not assume an AWS Load Balancer Controller.
secretFetchLoadBalancer:
enabled: false
# The ACM certificate of the HTTPS 443 listener. Required unless plaintextListener.
certificateArn: ""
# An HTTP 80 listener instead, for an ALB reached only through a TLS hop of its own
# (staging's AWS emulator). Never on a network the bearer token could be read from.
plaintextListener: false

reloader:
enabled: false

Expand Down
7 changes: 4 additions & 3 deletions cmd/loopzero-ops/internal/seed/broker.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ const (
var clusterCredentialGVK = schema.GroupVersionKind{Group: "loopzero.io", Version: "v1", Kind: "ClusterCredential"}

// brokerCellContext is the kube context of a cell's k3d cluster: infra/k3d names the
// cluster loopzero-<cellID>, and k3d prefixes its contexts with k3d-.
// cluster loopzero-<cellID>, and k3d prefixes its contexts with k3d-. It is the default
// of Deps.CellContextPrefix.
func brokerCellContext(cellID string) string { return "k3d-loopzero-" + cellID }

func (s *BrokerSeed) Run(d Deps) Result {
Expand All @@ -74,7 +75,7 @@ func (s *BrokerSeed) Run(d Deps) Result {
return Result{Verdict: FAIL, Reason: fmt.Sprintf("Layer 1 apply core Secret: %v", err)}
}
for _, cell := range cells {
cellCli, err := d.ClientFor(brokerCellContext(cell))
cellCli, err := d.ClientFor(d.cellContext(cell))
if err != nil {
return Result{Verdict: FAIL, Reason: fmt.Sprintf("Layer 2 resolve %s: %v", cell, err)}
}
Expand Down Expand Up @@ -114,7 +115,7 @@ func (s *BrokerSeed) Verify(d Deps) Result {
if want == "" {
return Result{Verdict: FAIL, Reason: fmt.Sprintf("core Secret has no broker token for %s", cell)}
}
cellCli, err := d.ClientFor(brokerCellContext(cell))
cellCli, err := d.ClientFor(d.cellContext(cell))
if err != nil {
return Result{Verdict: FAIL, Reason: fmt.Sprintf("resolve %s: %v", cell, err)}
}
Expand Down
33 changes: 33 additions & 0 deletions cmd/loopzero-ops/internal/seed/broker_cells_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,36 @@ func TestBrokerSeed_VerifyRefusesACellWhoseTokenDoesNotMatch(t *testing.T) {
t.Errorf("Verify = %s (%s), want FAIL naming cell-1", got.Verdict, got.Reason)
}
}

// On an environment whose kubeconfig names each cell's context after the cell id
// (staging's EKS clusters: cell-0, cell-1), the seed writes each cell's token through
// that context instead of the k3d one, which does not exist there.
func TestBrokerSeed_WritesThroughTheCellContextsTheEnvironmentNames(t *testing.T) {
mgmt := fake.NewClientBuilder().WithScheme(cellScheme(t)).WithObjects(
makeLoopZeroAPIDeploymentWithEnv(nil), clusterCredential("cell-0", "cell-0"),
).Build()
cell0 := fake.NewClientBuilder().WithScheme(newScheme(t)).Build()
noPrefix := ""
deps := Deps{
RolloutSettleTimeout: time.Millisecond,
Ctx: context.Background(),
Kube: NewKubeClient(mgmt),
CtrlClient: mgmt,
CellContextPrefix: &noPrefix,
ClientCtor: func(ctx string) (KubeClient, error) {
if ctx != "cell-0" {
t.Fatalf("seed asked for context %q, want cell-0", ctx)
}
return NewKubeClient(cell0), nil
},
}

if got := NewBrokerSeed().Run(deps); got.Verdict != PASS {
t.Fatalf("Verdict = %s (%s)", got.Verdict, got.Reason)
}

sec, err := NewKubeClient(cell0).GetSecret(deps.Ctx, brokerESONamespace, brokerSecretName)
if err != nil || len(sec.Data[brokerTokenKey]) == 0 {
t.Fatalf("cell-0 holds no broker token (err=%v)", err)
}
}
13 changes: 13 additions & 0 deletions cmd/loopzero-ops/internal/seed/seed.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,19 @@ type Deps struct {
// cmd/loopzero-ops suite, and that cost kept the gate tests off the push path
// (B-101, and item 2 of B-088).
RolloutSettleTimeout time.Duration
// CellContextPrefix is what a cell's kube context is named, before its cell id.
// Nil keeps the k3d convention (`k3d-loopzero-<cell>`); an environment whose
// kubeconfig names each context after the cell id (staging's EKS clusters) sets it
// to "". The composition root reads it from LOOPZERO_CELL_CONTEXT_PREFIX.
CellContextPrefix *string
}

// cellContext is the kube context of cellID under CellContextPrefix.
func (d Deps) cellContext(cellID string) string {
if d.CellContextPrefix == nil {
return brokerCellContext(cellID)
}
return *d.CellContextPrefix + cellID
}

// settleTimeout resolves the effective wait: an injected value wins, and zero
Expand Down
13 changes: 13 additions & 0 deletions cmd/loopzero-ops/seed_subcmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,9 +195,22 @@ func buildSeedDeps(dryRun bool) (seed.Deps, error) {
// nowhere else: that is what stops each seed from reading the environment
// on its own and answering the same question a different way.
Policy: seed.PolicyFromEnvironment(),
// LOOPZERO_CELL_CONTEXT_PREFIX names the cells' kube contexts, set even when
// empty: staging's kubeconfig names each one after the cell id. Unset keeps
// the k3d names.
CellContextPrefix: cellContextPrefixFromEnvironment(),
}, nil
}

// cellContextPrefixFromEnvironment is LOOPZERO_CELL_CONTEXT_PREFIX when it is set, empty
// included, and nil when it is not.
func cellContextPrefixFromEnvironment() *string {
if v, ok := os.LookupEnv("LOOPZERO_CELL_CONTEXT_PREFIX"); ok {
return &v
}
return nil
}

// buildKubeClient resolves a controller-runtime client for the given kubeconfig
// context name. The empty string uses the default context (equivalent to
// `kubectl` without --context). Multi-cluster seeds request build/workload/vault
Expand Down
Loading
Loading