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
2 changes: 1 addition & 1 deletion backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ require (
github.com/hashicorp/hcl/v2 v2.25.0
github.com/jackc/pgx/v5 v5.10.0
github.com/michielvha/logger v0.0.5
github.com/michielvha/stackweaver/core v0.631.8
github.com/michielvha/stackweaver/core v0.631.9
github.com/redis/go-redis/v9 v9.23.0
github.com/robfig/cron/v3 v3.0.1
github.com/zclconf/go-cty v1.19.0
Expand Down
4 changes: 2 additions & 2 deletions backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,8 @@ github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/michielvha/logger v0.0.5 h1:zcepKGWRMgo32j6nU++RBWtzzz2Q5txVquGDbaSlCro=
github.com/michielvha/logger v0.0.5/go.mod h1:YJjpbm0AlPmmLBFO8tPyBAruWMJisu2sPo/DX9qxKJk=
github.com/michielvha/stackweaver/core v0.631.8 h1:Qkuq41VnfKltbcQdWVEilNANLm7PDreU4iZCNLjTrsk=
github.com/michielvha/stackweaver/core v0.631.8/go.mod h1:Bt8/peil8riL5pzhiLbkoT5b9d30PH+GYKQVpfeqKKI=
github.com/michielvha/stackweaver/core v0.631.9 h1:hmtEVOfDOVfRWzUAITlzyfkEUmznvNTQxqQVKcjqCKo=
github.com/michielvha/stackweaver/core v0.631.9/go.mod h1:Bt8/peil8riL5pzhiLbkoT5b9d30PH+GYKQVpfeqKKI=
github.com/microsoft/go-mssqldb v1.7.2 h1:CHkFJiObW7ItKTJfHo1QX7QBBD1iV+mn1eOyRP3b/PA=
github.com/microsoft/go-mssqldb v1.7.2/go.mod h1:kOvZKUdrhhFQmxLZqbwUV0rHkNkZpthMITIb2Ko1IoA=
github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Copyright (c) 2026 VH & Co BV. Licensed under the Business Source License 1.1. See LICENSE for details.

package ansible

import (
"encoding/json"
"strings"
"testing"

"github.com/google/uuid"
"github.com/michielvha/stackweaver/core/models"
)

// The job API shows a sensitive variable's key with the placeholder, never its sealed value.
func TestFormatJobResponse_ShowsSensitiveVariablesAsThePlaceholder(t *testing.T) {
job := &models.AnsibleJob{
ID: uuid.New(),
ExtraVars: models.JobExtraVars{"region": "eu-west"},
SecretExtraVars: models.JobSecretVars{"db_password": "sealed-ciphertext"},
}
res := formatJobResponse(job)
if got := res.Attributes.ExtraVars["db_password"]; got != models.EncryptedPlaceholder {
t.Errorf("db_password = %v, want %q", got, models.EncryptedPlaceholder)
}
if got := res.Attributes.ExtraVars["region"]; got != "eu-west" {
t.Errorf("region = %v, want eu-west", got)
}
if _, ok := job.ExtraVars["db_password"]; ok {
t.Error("formatting the response changed the job's stored extra vars")
}
body, err := json.Marshal(res)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(body), "sealed-ciphertext") {
t.Errorf("the response holds the sealed value: %s", body)
}
// Nothing that serialises the job itself carries the sealed values.
raw, err := json.Marshal(job)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(raw), "sealed-ciphertext") {
t.Errorf("the job's JSON holds the sealed value: %s", raw)
}
}
18 changes: 17 additions & 1 deletion backend/internal/api/v2/handlers/ansible/jobs.go
Original file line number Diff line number Diff line change
Expand Up @@ -931,14 +931,30 @@ func (h *JobHandler) LaunchFromTemplate(c *gin.Context) {
jsonapi.WriteDocument(c, http.StatusCreated, formatJobResponse(job))
}

// shownExtraVars is a job's extra vars as the job API shows them: the stored values, and each
// sensitive variable's key with models.EncryptedPlaceholder in place of its value.
func shownExtraVars(job *models.AnsibleJob) models.JobExtraVars {
if len(job.SecretExtraVars) == 0 {
return job.ExtraVars
}
shown := make(models.JobExtraVars, len(job.ExtraVars)+len(job.SecretExtraVars))
for k, v := range job.ExtraVars {
shown[k] = v
}
for k := range job.SecretExtraVars {
shown[k] = models.EncryptedPlaceholder
}
return shown
}

// formatJobResponse formats a job for JSON:API response
func formatJobResponse(job *models.AnsibleJob) jsonapi.Resource[JobAttributes] {
attributes := JobAttributes{
Name: job.Name,
JobType: job.JobType,
PlaybookName: job.PlaybookName,
Status: job.Status,
ExtraVars: job.ExtraVars,
ExtraVars: shownExtraVars(job),
Limit: job.Limit,
Tags: job.Tags,
SkipTags: job.SkipTags,
Expand Down
30 changes: 29 additions & 1 deletion backend/internal/api/v2/handlers/runner_agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -2029,10 +2029,38 @@ func (h *RunnerAgentHandler) GetJobArtifacts(c *gin.Context) {
}
}

// Get extra vars (already in job)
// The job's extra vars, with its sensitive variables decrypted: the executor is the only
// reader of those values.
if job.ExtraVars != nil {
response.ExtraVars = job.ExtraVars
}
if len(job.SecretExtraVars) > 0 {
// Only the job token of the job's current attempt, which authorizeRunnerForAnsibleJob has
// bound above, receives them: never a launcher's own token.
if _, ok := callingJob(c); !ok {
writeRunnerForbidden(c, "this job's sensitive variables are given only to its job token")
return
}
if h.cryptoService == nil {
logger.Errorf("Job %s: its sensitive variables cannot be decrypted: no encryption key", job.ID)
jsonapi.WriteErrorNoDetail(c, http.StatusInternalServerError, "Internal Server Error")
return
}
secret, err := ansible.OpenSecretVars(job.SecretExtraVars, h.cryptoService.Decrypt)
if err != nil {
logger.Errorf("Job %s: %v", job.ID, err)
jsonapi.WriteErrorNoDetail(c, http.StatusInternalServerError, "Internal Server Error")
return
}
merged := make(models.JobExtraVars, len(job.ExtraVars)+len(secret))
for k, v := range job.ExtraVars {
merged[k] = v
}
for k, v := range secret {
merged[k] = v
}
response.ExtraVars = merged
}

// Workload identity: the platform-minted per-run tokens for Azure, AWS, GCP and Vault, the same
// four an OpenTofu run's artifacts carry (#933, D2, D8, AC37).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,32 @@ import (
"github.com/gin-gonic/gin"
"github.com/michielvha/stackweaver/backend/internal/api/middleware"
"github.com/michielvha/stackweaver/backend/internal/services/apikey"
"github.com/michielvha/stackweaver/core/crypto"
"github.com/michielvha/stackweaver/core/models"
"github.com/michielvha/stackweaver/core/repository"
"github.com/michielvha/stackweaver/core/runnercontract"
"github.com/michielvha/stackweaver/core/services/vcs"
)

// secretVarsTestKey is the Ansible encryption key jobTokenRouterWithCrypto's handler holds.
var secretVarsTestKey = []byte("0123456789abcdef0123456789abcdef")

// jobTokenRouter wires the job-token route and the job-data routes the way SetupV2Routes does.
func (f *agentPrepFixture) jobTokenRouter() (*gin.Engine, *apikey.Service) {
return f.jobTokenRouterWith(nil)
}

// jobTokenRouterWithCrypto is jobTokenRouter with a handler that holds secretVarsTestKey.
func (f *agentPrepFixture) jobTokenRouterWithCrypto(t *testing.T) (*gin.Engine, *apikey.Service) {
t.Helper()
cs, err := crypto.NewCryptoService(secretVarsTestKey)
if err != nil {
t.Fatal(err)
}
return f.jobTokenRouterWith(cs)
}

func (f *agentPrepFixture) jobTokenRouterWith(cs *crypto.CryptoService) (*gin.Engine, *apikey.Service) {
svc := apikey.NewService(repository.NewAPIKeyRepository(f.db), nil, nil, nil)
playbookRepo := repository.NewAnsiblePlaybookRepository(f.db)
registry := vcs.NewProviderRegistry(nil, nil, nil, nil)
Expand All @@ -42,6 +60,7 @@ func (f *agentPrepFixture) jobTokenRouter() (*gin.Engine, *apikey.Service) {
playbookRepo: playbookRepo,
vcsRegistry: registry,
storageClient: newSnapshotStore(),
cryptoService: cs,
}
return f.router(func(authed *gin.RouterGroup) {
authed.POST("/jobs/:id/token", middleware.RequireRunnerToken(), h.JobToken)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// Copyright (c) 2026 VH & Co BV. Licensed under the Business Source License 1.1. See LICENSE for details.

// A job's sensitive variables leave the API only in its job-token artifacts, decrypted.
//
// Gated behind `integration`; skips unless $TEST_DATABASE_URL is set. Run with:
//
// go test -tags integration ./internal/api/v2/handlers/ -run TestJobArtifacts_SensitiveVariables

//go:build integration

package handlers

import (
"encoding/json"
"net/http"
"strings"
"testing"

"github.com/michielvha/stackweaver/core/crypto"
"github.com/michielvha/stackweaver/core/models"
"gorm.io/gorm"
)

func TestJobArtifacts_SensitiveVariablesReachOnlyTheExecutor(t *testing.T) {
f := setupAgentPrepFixture(t)
r, svc := f.jobTokenRouterWithCrypto(t)

cs, err := crypto.NewCryptoService(secretVarsTestKey)
if err != nil {
t.Fatal(err)
}
sealed, err := cs.Encrypt(`"s3cret-value"`)
if err != nil {
t.Fatal(err)
}
job := f.seedJob(t, nil, f.runnerA1)
if err := f.db.Model(&models.AnsibleJob{}).Where("id = ?", job.ID).Updates(map[string]any{
"extra_vars": models.JobExtraVars{"region": "eu-west"},
"secret_extra_vars": models.JobSecretVars{"db_password": sealed},
}).Error; err != nil {
t.Fatalf("storing the job's variables: %v", err)
}
if code, _ := f.mintJobToken(t, r, svc, "a1", job.ID.String(), "job"); code != http.StatusOK {
t.Fatalf("mint: %d", code)
}

rec := runnerDo(t, r, "job", http.MethodGet, "/api/v2/runner/jobs/"+job.ID.String()+"/artifacts", nil)
if rec.Code != http.StatusOK {
t.Fatalf("artifacts: status %d (%s)", rec.Code, rec.Body.String())
}
var arts struct {
ExtraVars map[string]any `json:"extra_vars"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &arts); err != nil {
t.Fatalf("decoding the artifacts: %v", err)
}
if arts.ExtraVars["db_password"] != "s3cret-value" || arts.ExtraVars["region"] != "eu-west" {
t.Errorf("artifacts extra_vars = %v, want the decrypted db_password and region", arts.ExtraVars)
}
}

// seedSecretJob seeds a job claimed by runner a1 that holds one sensitive variable.
func (f *agentPrepFixture) seedSecretJob(t *testing.T) *models.AnsibleJob {
t.Helper()
cs, err := crypto.NewCryptoService(secretVarsTestKey)
if err != nil {
t.Fatal(err)
}
sealed, err := cs.Encrypt(`"s3cret-value"`)
if err != nil {
t.Fatal(err)
}
job := f.seedJob(t, nil, f.runnerA1)
if err := f.db.Model(&models.AnsibleJob{}).Where("id = ?", job.ID).
Update("secret_extra_vars", models.JobSecretVars{"db_password": sealed}).Error; err != nil {
t.Fatalf("storing the job's sensitive variable: %v", err)
}
return job
}

func TestJobArtifacts_SensitiveVariablesNeedTheJobsCurrentToken(t *testing.T) {
f := setupAgentPrepFixture(t)
r, svc := f.jobTokenRouterWithCrypto(t)
job := f.seedSecretJob(t)
other := f.seedJob(t, nil, f.runnerA1)
path := "/api/v2/runner/jobs/" + job.ID.String() + "/artifacts"

// The launcher's own token, whether or not it declared the job-token capability.
if rec := runnerDo(t, r, "a1", http.MethodGet, path, nil); rec.Code != http.StatusForbidden || strings.Contains(rec.Body.String(), "s3cret-value") {
t.Errorf("the launcher's token: status %d, want 403 without the value (%s)", rec.Code, rec.Body.String())
}
// Another job's token.
if code, _ := f.mintJobToken(t, r, svc, "a1", other.ID.String(), "other"); code != http.StatusOK {
t.Fatalf("mint for the other job: %d", code)
}
if rec := runnerDo(t, r, "other", http.MethodGet, path, nil); rec.Code != http.StatusForbidden || strings.Contains(rec.Body.String(), "s3cret-value") {
t.Errorf("another job's token: status %d, want 403 without the value (%s)", rec.Code, rec.Body.String())
}
// The job's own token, once a later attempt exists.
if code, _ := f.mintJobToken(t, r, svc, "a1", job.ID.String(), "job"); code != http.StatusOK {
t.Fatalf("mint: %d", code)
}
if err := f.db.Model(&models.AnsibleJob{}).Where("id = ?", job.ID).Update("attempt", gorm.Expr("attempt + 1")).Error; err != nil {
t.Fatal(err)
}
if rec := runnerDo(t, r, "job", http.MethodGet, path, nil); rec.Code != http.StatusForbidden || strings.Contains(rec.Body.String(), "s3cret-value") {
t.Errorf("a superseded attempt's token: status %d, want 403 without the value (%s)", rec.Code, rec.Body.String())
}
}

// A launcher that registered without the job-token capability reaches a job's other artifacts
// with its own token, as before, but not one whose job holds sensitive variables.
func TestJobArtifacts_ALegacyLauncherTokenGetsNoSensitiveVariables(t *testing.T) {
f := setupAgentPrepFixture(t)
r, _ := f.jobTokenRouterWithCrypto(t)
if err := f.db.Model(&models.Runner{}).Where("id = ?", f.runnerA1.ID).Update("capabilities", gorm.Expr("'[]'::jsonb")).Error; err != nil {
t.Fatalf("clearing the launcher's capabilities: %v", err)
}
plain := f.seedJob(t, nil, f.runnerA1)
if rec := runnerDo(t, r, "a1", http.MethodGet, "/api/v2/runner/jobs/"+plain.ID.String()+"/artifacts", nil); rec.Code != http.StatusOK {
t.Errorf("a plain job's artifacts with a legacy launcher token: status %d, want 200 (%s)", rec.Code, rec.Body.String())
}
job := f.seedSecretJob(t)
rec := runnerDo(t, r, "a1", http.MethodGet, "/api/v2/runner/jobs/"+job.ID.String()+"/artifacts", nil)
if rec.Code != http.StatusForbidden || strings.Contains(rec.Body.String(), "s3cret-value") {
t.Errorf("a legacy launcher token: status %d, want 403 without the value (%s)", rec.Code, rec.Body.String())
}
}
Loading