Skip to content

Added audit activities when secret variables are upserted - #49412

Merged
juan-fdz-hawa merged 1 commit into
mainfrom
16779-emit-activities-on-secret-upsert-endpoint
Jul 16, 2026
Merged

Added audit activities when secret variables are upserted#49412
juan-fdz-hawa merged 1 commit into
mainfrom
16779-emit-activities-on-secret-upsert-endpoint

Conversation

@juan-fdz-hawa

@juan-fdz-hawa juan-fdz-hawa commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Added audit activities when secret variables are created or updated through the PUT /api/latest/fleet/spec/secret_variables endpoint

Checklist for submitter

If some of the following don't apply, delete the relevant line.

  • Changes file added for user-visible changes in changes/, orbit/changes/ or ee/fleetd-chrome/changes.
    See Changes files for more information.

Testing

  • Added/updated automated tests
  • QA'd all new/changed functionality manually

Summary by CodeRabbit

  • New Features
    • Added audit activity tracking for secret variable creation and updates, emitted per variable as appropriate.
    • Added a new activity type for custom variable updates, including the affected custom variable name in the payload.
    • Updated the activity feed to render “updated custom variable” entries.
    • Extended the activity filter dropdown to include the new “updated custom variable” activity type (with dry runs and no-ops producing no new activities).

results, err := ds.GetSecretVariables(ctx, nil)
assert.NoError(t, err)
assert.Empty(t, results)
require.NoError(t, err)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed assert -> require for consistency sake

ctx,
user,
fleet.ActivityCreatedCustomVariable{
CustomVariableName: name,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The variable ID is not used anywhere so omitting it here is fine

@codecov

codecov Bot commented Jul 16, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 60.52632% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.16%. Comparing base (01bb250) to head (f4c9b27).

Files with missing lines Patch % Lines
server/datastore/mysql/secret_variables.go 50.00% 6 Missing ⚠️
...vityFeed/GlobalActivityItem/GlobalActivityItem.tsx 0.00% 5 Missing ⚠️
server/service/secret_variables.go 80.95% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##             main   #49412    +/-   ##
========================================
  Coverage   68.16%   68.16%            
========================================
  Files        3855     3856     +1     
  Lines      243602   244207   +605     
  Branches    13008    13010     +2     
========================================
+ Hits       166045   166468   +423     
- Misses      62559    62695   +136     
- Partials    14998    15044    +46     
Flag Coverage Δ
backend 69.66% <69.69%> (+<0.01%) ⬆️
frontend 60.14% <0.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Secret variable upserts now return created and updated variable names. The service emits audit activities for each changed variable, including a new updated-custom-variable activity payload. Backend, datastore, mock, and integration tests cover creation, updates, unchanged values, dry runs, and GitOps execution. The frontend adds the activity type, filter label, and activity-feed rendering.

Possibly related PRs

  • fleetdm/fleet#49354: Also changes secret-variable upsert handling for actions triggered by changed secret names.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed It clearly matches the PR’s main change: audit activity for secret variable upserts.
Description check ✅ Passed It includes the change summary and the key checklist items for changes files and testing.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 16779-emit-activities-on-secret-upsert-endpoint

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ast-grep (0.44.1)
server/service/integration_core_test.go

ast-grep timed out on this file

server/service/integration_mdm_test.go

ast-grep timed out on this file


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@server/datastore/mysql/secret_variables_test.go`:
- Around line 102-116: In the test flow around GetSecretVariables, change the
post-update length assertion to validate the newly fetched updated slice rather
than rechecking original, ensuring updated[0] is guarded before the equality
assertion.

In `@server/service/secret_variables.go`:
- Around line 59-88: The secret-variable activity loops currently return on the
first svc.NewActivity failure after persistence, preventing remaining audit
events from being emitted. Update the created and updated loops to log
activity-emission errors and continue processing all names, while preserving the
successful upsert result and avoiding a whole-request failure caused solely by
NewActivity.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2919b101-3d65-4ae4-bbe4-6cecb1a7095f

📥 Commits

Reviewing files that changed from the base of the PR and between 621ede7 and 8f2edca.

⛔ Files ignored due to path filters (1)
  • docs/Contributing/reference/audit-logs.md is excluded by !**/*.md
📒 Files selected for processing (12)
  • changes/16779-secret-variable-spec-activities
  • frontend/interfaces/activity.ts
  • frontend/pages/DashboardPage/cards/ActivityFeed/GlobalActivityItem/GlobalActivityItem.tsx
  • server/datastore/mysql/secret_variables.go
  • server/datastore/mysql/secret_variables_test.go
  • server/datastore/mysql/software_installers_test.go
  • server/fleet/activities.go
  • server/fleet/datastore.go
  • server/mock/datastore_mock.go
  • server/service/integration_core_test.go
  • server/service/secret_variables.go
  • server/service/secret_variables_test.go

Comment thread server/datastore/mysql/secret_variables_test.go
Comment thread server/service/secret_variables.go
@juan-fdz-hawa
juan-fdz-hawa force-pushed the 16779-emit-activities-on-secret-upsert-endpoint branch from 1ef7578 to f4c9b27 Compare July 16, 2026 17:22

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@server/service/secret_variables_test.go`:
- Around line 110-115: Remove t.Parallel() from
TestCreateSecretVariablesEmitsActivities so it cannot race with
TestCreateSecretVariables while that test changes the package-global
testSetEmptyPrivateKey; preserve the test’s existing setup and assertions.
- Around line 117-140: Update CreateSecretVariables and its test coverage so
secret-variable persistence and all corresponding activity records are
failure-atomic: when any NewActivity call fails, neither the upsert nor earlier
activities may remain committed, or the missing activity must be durably
retried. Add a test that injects a later ActivityMock.NewActivity failure and
verifies the required rollback or durable retry behavior, while preserving
separate created and updated activity emission.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: af51b154-d9b4-43fc-accb-3768b3b6e2bf

📥 Commits

Reviewing files that changed from the base of the PR and between 1ef7578 and f4c9b27.

⛔ Files ignored due to path filters (1)
  • docs/Contributing/reference/audit-logs.md is excluded by !**/*.md
📒 Files selected for processing (14)
  • changes/16779-secret-variable-spec-activities
  • cmd/fleetctl/fleetctl/gitops_test.go
  • frontend/interfaces/activity.ts
  • frontend/pages/DashboardPage/cards/ActivityFeed/GlobalActivityItem/GlobalActivityItem.tsx
  • server/datastore/mysql/secret_variables.go
  • server/datastore/mysql/secret_variables_test.go
  • server/datastore/mysql/software_installers_test.go
  • server/fleet/activities.go
  • server/fleet/datastore.go
  • server/mock/datastore_mock.go
  • server/service/integration_core_test.go
  • server/service/integration_mdm_test.go
  • server/service/secret_variables.go
  • server/service/secret_variables_test.go
🚧 Files skipped from review as they are similar to previous changes (7)
  • changes/16779-secret-variable-spec-activities
  • server/fleet/activities.go
  • server/fleet/datastore.go
  • server/datastore/mysql/secret_variables.go
  • server/service/secret_variables.go
  • server/mock/datastore_mock.go
  • server/service/integration_core_test.go

Comment on lines +110 to +115
func TestCreateSecretVariablesEmitsActivities(t *testing.T) {
t.Parallel()
ds := new(mock.Store)
opts := &TestServerOpts{}
svc, ctx := newTestService(t, ds, nil, nil, opts)
ctx = viewer.NewContext(ctx, viewer.Viewer{User: &fleet.User{ID: 1, GlobalRole: new(fleet.RoleAdmin)}})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Do not run this test in parallel with the global private-key override.

TestCreateSecretVariables also runs in parallel and temporarily sets package-global testSetEmptyPrivateKey. This test can consequently fail with the missing-private-key error. Remove t.Parallel() or replace the global override with per-service state.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@server/service/secret_variables_test.go` around lines 110 - 115, Remove
t.Parallel() from TestCreateSecretVariablesEmitsActivities so it cannot race
with TestCreateSecretVariables while that test changes the package-global
testSetEmptyPrivateKey; preserve the test’s existing setup and assertions.

Comment on lines +117 to +140
t.Run("emits a created activity per created variable and an updated activity per updated variable", func(t *testing.T) {
ds.UpsertSecretVariablesFunc = func(ctx context.Context, secrets []fleet.SecretVariable) (created []string, updated []string, err error) {
return []string{"CREATED"}, []string{"UPDATED"}, nil
}
var activities []activity_api.ActivityDetails
opts.ActivityMock.NewActivityFunc = func(_ context.Context, _ *activity_api.User, activity activity_api.ActivityDetails) error {
activities = append(activities, activity)
return nil
}
err := svc.CreateSecretVariables(ctx, []fleet.SecretVariable{
{Name: "FLEET_SECRET_CREATED", Value: "a"},
{Name: "FLEET_SECRET_UPDATED", Value: "b"},
}, false)
require.NoError(t, err)
require.Len(t, activities, 2)

createdActivity, ok := activities[0].(fleet.ActivityCreatedCustomVariable)
require.True(t, ok)
require.Equal(t, "CREATED", createdActivity.CustomVariableName)

updatedActivity, ok := activities[1].(fleet.ActivityUpdatedCustomVariable)
require.True(t, ok)
require.Equal(t, "UPDATED", updatedActivity.CustomVariableName)
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Make secret changes and audit records failure-atomic.

The upsert commits before activities are written individually. If a later NewActivity fails, secrets and earlier activities remain persisted; retrying sees unchanged variables and never emits the missing audit record. Add failure coverage and use a transaction, outbox, or durable retry mechanism.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@server/service/secret_variables_test.go` around lines 117 - 140, Update
CreateSecretVariables and its test coverage so secret-variable persistence and
all corresponding activity records are failure-atomic: when any NewActivity call
fails, neither the upsert nor earlier activities may remain committed, or the
missing activity must be durably retried. Add a test that injects a later
ActivityMock.NewActivity failure and verifies the required rollback or durable
retry behavior, while preserving separate created and updated activity emission.

@juan-fdz-hawa
juan-fdz-hawa merged commit 0d3a3bd into main Jul 16, 2026
50 checks passed
@juan-fdz-hawa
juan-fdz-hawa deleted the 16779-emit-activities-on-secret-upsert-endpoint branch July 16, 2026 22:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants