Skip to content

Manage Salt master clusters - #70656

Merged
dwoz merged 71 commits into
saltstack:masterfrom
dwoz:wip-remote-cli-rebased
Nov 5, 2026
Merged

dwoz merged 71 commits into
saltstack:masterfrom
dwoz:wip-remote-cli-rebased

Conversation

@dwoz

@dwoz dwoz commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

What this adds

You can now run salt, salt-run, and salt-key from your laptop against a remote Salt master.

Until now, if you wanted to drive a master without being logged into it, you either had to SSH into it, or stand up salt-api and talk HTTP, or write a Python script against LocalClient. None of those are terrible, but none of them let you just use the regular commands from somewhere else.

This PR lets you install Salt on any workstation, point it at a master with a short config file, and run the normal commands.

How you'd use it

On your workstation:

pip install salt

Create /etc/salt/client:

master: salt-master.example.com
client_id: alice-laptop

Then just run a command:

salt '*' test.ping

The first time it runs, the client generates its own keypair and sends the public key to the master — same handshake a minion does on first contact. On the master, accept it:

salt-key -L           # shows alice-laptop as pending
salt-key -a alice-laptop

From then on, the normal commands just work:

salt '*' test.ping
salt-run manage.up
salt-key -L

Same commands, same output, same return shapes you'd see on the master itself. Nothing new to learn.

How it works, briefly

Your workstation signs in to the master using the same PKI handshake a minion uses, and gets an encrypted session. Credentials and requests travel over that encrypted session. On the master side, requests get dispatched through the same code path salt-api already uses, so authorization, ACLs, and eauth all behave the same way they always have.

Job returns and orchestration events come back over a separate encrypted event stream (one subprocess per master), with a session key that only your client can read.

What's in the branch

New config role: a /etc/salt/client file turns Salt into client mode. It honors master_finger for TOFU pinning and master_port for load balancers.

New Python clients, documented in the client API reference: RemoteClient, RemoteRunnerClient, RemoteRunner, RemoteWheelClient, ClientEventSubscriber. If you've used LocalClient or RunnerClient before, these feel identical.

Master-side plumbing: a new auth type for pure-PKI clients, a batch_adopt endpoint so --batch jobs survive client disconnect, a check that stops a minion and a client from sharing the same name, and a separate PKI subtree for client keys that works correctly in cluster mode.

Encrypted event stream: each client session gets its own session key, buffers are bounded, and the auth channel speaks msgpack end-to-end. (An earlier draft of this feature used pickle on the pre-auth path, which would have been a remote code execution bug. Replaced before merge.)

Stackable authorization: you can require both a PKI identity and an eauth principal on the same request. Useful for "Alice's laptop can run state.apply, but only when she's also authenticated to corporate SSO".

Scenario tests under tests/pytests/scenarios/client/ cover a containerized master, a 3-master cluster sharing one PKI directory, and the same 3-master cluster behind a round-robin TCP proxy.

One unrelated fix (flagged for split-out)

salt/utils/templates.py raises Python's recursion limit for the duration of a Jinja render and restores it after. This fixes test_orchestration_with_pillar_dot_items on Python 3.14 under coverage, which was failing with "maximum recursion depth exceeded".

This is not a remote-CLI change — it's an older Jinja bug this branch happens to trip. It's clearly flagged in the code with a SPLIT-OUT CANDIDATE comment so reviewers can lift it into a standalone PR with its own regression test.

What's not in this PR

salt-run --doc still renders locally on the client instead of making a round-trip to the master. It's just help text; there's no reason to send it over the network. Everything else does route to the master.

Test plan

  • CI green on all platforms
  • New scenario tests pass under tests/pytests/scenarios/client/
  • Existing LocalClient, RunnerClient, WheelClient, and salt-key behavior on the master host is unchanged
  • The orchestration test above passes on Python 3.14 under coverage

@dwoz
dwoz requested a review from a team as a code owner November 3, 2026 10:11
@dwoz dwoz added the test:full Run the full test suite label Nov 3, 2026
@dwoz dwoz added this to the Potassium v3009.0 milestone Nov 3, 2026
@dwoz dwoz changed the title Manage Salt master clusters anywhere Manage Salt master clusters Nov 3, 2026
dwoz added 10 commits November 3, 2026 17:37
This commit rebases the remote CLI client authentication and ACL
implementation from the 6-month-old base (713a923) onto the
current master (021a041 - 2,111 commits ahead).

Resolved Conflicts:
- salt/cli/key.py: Combined context manager with client_auth check
- salt/config/__init__.py: Merged tracing/metrics configs with encryption configs
- salt/crypt.py: Combined role-based PKI paths with _creds bug fix
- salt/daemons/masterapi.py: Added wheel and client ACL initialization
- salt/channel/server.py: Kept updated auth logic and class structure
- tests/pytests/unit/test_master.py: Merged test fixture configurations

salt/master.py Resolution:
Accepted master's version due to extensive refactoring (8 conflicts).
The client ACL publish checks from our implementation need to be
re-applied in a follow-up commit. Original logic is in wip-remote-cli
branch for reference.

Next Steps:
1. Re-add client ACL checking to salt/master.py minion_publish()
2. Run full test suite to verify functionality
3. Update any broken tests due to master refactoring
After rebasing onto the latest master (2,111 commits), the client ACL
logic that was in the old publish() method needed to be re-added to the
new refactored publish() method in ClearFuncs.

Changes:
- Added client_acl initialization in AESFuncs.__init__
- Added client detection logic that checks if the username is in
  client_keys cache (indicates client authentication)
- Added client ACL checking that:
  * Checks blacklist first (takes precedence)
  * Uses ClientACL helper to check publish permissions
  * Logs success and sets username in clear_load
- Modified standard authorization check to skip for clients since
  they use client ACL instead

All 35 client ACL tests pass:
- 4 runner ACL tests
- 3 wheel ACL tests
- 2 ACL error message tests
- 4 backward compatibility tests
- 2 multiple clients tests
- 2 ACL revocation tests
- 2 unknown client tests
- 14 publish ACL tests (new)
- 2 publish error message tests

Also verified:
- 12/12 client authentication tests pass
- 9/9 client lifecycle scenario tests pass

The rebase is now complete with all client ACL functionality preserved
and working correctly on the latest master.
The publish() method in ClearFuncs was accessing self.key_cache and
self.client_acl, but these were only initialized in AESFuncs.__init__.

Added initialization of both attributes in ClearFuncs.__init__ to
fix the pylint error:
  E1101(no-member): Instance of 'ClearFuncs' has no 'key_cache' member

This ensures that publish() in ClearFuncs can properly check client
authentication and enforce ACLs.
During the rebase, authentication code (lines 688-724) was incorrectly
merged into the ReqServerChannel.close() method in salt/channel/server.py.

This caused pylint errors:
  E0602(undefined-variable): Undefined variable 'load'
  E0602(undefined-variable): Undefined variable 'sign_messages'
  E0602(undefined-variable): Undefined variable 'sig_algo'

Fixed by removing the misplaced authentication code that was using
undefined variables within the close() method. The close() method
now correctly ends after cleaning up ckminions, as in upstream master.

Verified with:
- pylint: 10.00/10 rating
- test_client_auth_payload_structure: PASSED
Black formatting check failed because there were 3 extra blank lines
in salt/config/__init__.py that need to be removed:
- Line 1999: After eauth_tokens.cluster_id
- Line 2070: After metrics config block
- Line 2074: After signing_algorithm
The salt command should use LocalClient by default (for local master
usage) and only use RemoteClient when the --client-auth flag is passed.
This maintains backwards compatibility with existing salt deployments.

Changes:
- salt/cli/salt.py: Use get_local_client() by default, get_remote_client()
  only when --client-auth is specified
- salt/utils/parsers.py: Add --client-auth flag to SaltCMDOptionParser

This makes the salt command consistent with salt-run and salt-key, where
--client-auth is an opt-in flag for remote PKI-based authentication.
Eliminate the need for explicit --client-auth flags in most cases by
automatically detecting the appropriate authentication method based on
the environment.

Detection logic for all commands (salt, salt-run, salt-key):

1. If --client-auth is explicitly set (True/False), respect that choice
2. Otherwise, auto-detect:
   - Try traditional local execution (LocalClient or user permission check)
   - If that fails AND client keys exist, automatically use RemoteClient
   - If neither works, fail with appropriate error

Benefits:
- Backwards compatible: existing local deployments work unchanged
- Zero configuration for remote: once client keys are accepted, remote
  execution "just works" without flags
- Explicit control still available via --client-auth flag when needed

Examples:
- On master with proper permissions: Uses LocalClient (traditional)
- On remote machine with client keys: Uses RemoteClient (automatic)
- No keys, no permissions: Fails with clear error message
Introduces a dedicated client configuration file that allows managing
connections to multiple Salt masters through profiles.

Features:
- Dedicated /etc/salt/client config file
- Profile support for switching between masters
- Automatic fallback to /etc/salt/master (backwards compatible)
- User overrides via ~/.saltrc still work

Configuration example (/etc/salt/client):
```yaml
# Default connection (used when no --profile specified)
master: localhost
id: admin-laptop

# Multiple master profiles
profiles:
  prod:
    master: prod-salt.example.com
    id: admin-laptop-prod
  dev:
    master: dev-salt.example.com
    id: admin-laptop-dev
```

Usage:
- salt --profile=prod '*' test.ping
- salt-run --profile=dev jobs.list_jobs
- salt-key --profile=prod -L

Benefits:
- One config file for all CLI tools (salt, salt-run, salt-key)
- Easy switching between multiple masters
- Backwards compatible with existing /etc/salt/master usage
- Default behavior unchanged (local master via IPC)
Adds network-based event delivery so RemoteClient can work from
machines that are not on the Salt master.

## Architecture

**Client Event Publisher (Port 4507)**
- Runs as separate process on the master
- Requires client PKI authentication
- Subscribes to master event bus (IPC)
- Filters and publishes events to authenticated clients

**Client Event Subscriber**
- Network-based event subscription for RemoteClient
- Authenticates using client keys
- Subscribes to specific job events
- Receives filtered events over TCP

## Event Filtering

Clients only receive events for:
- Jobs they initiated (by JID)
- Events they explicitly subscribe to

System/admin events are filtered out for security.

## Components

**salt/utils/client_event.py** (new file)
- ClientEventPublisher: Master-side authenticated event publisher
- ClientEventSubscriber: Client-side network event subscriber

**salt/client/__init__.py**
- RemoteClient now uses ClientEventSubscriber instead of IPC
- Automatically subscribes to job events on pub()
- Fixed master_uri to use configured master, not interface

**salt/config/__init__.py**
- Added client_event_port config (default: 4507)
- Added client_event_publish config (default: True)

**salt/master.py**
- Integrated ClientEventPublisher into master daemon startup
- Started alongside other master processes

## Benefits

✅ Remote CLI tools work from any machine (not just on master)
✅ No salt-api required
✅ Secure (requires client key authentication)
✅ Event filtering prevents information leakage
✅ Backwards compatible (can be disabled)

## Configuration

Enable/disable in master config:
```yaml
client_event_publish: True  # Enable event publisher
client_event_port: 4507      # Publisher port
```

## Usage

RemoteClient now works transparently from remote machines:
```python
# On a laptop (not on the master)
client = salt.client.get_remote_client(profile='prod')
client.cmd('*', 'test.ping')  # Works! Events streamed over network
```
This commit enables salt-run (RunnerClient) and salt-key (WheelClient)
to work fully remotely by adding intelligent network event detection.

Changes:
- Add _should_use_network_events() method to RunnerClient and WheelClient
- Auto-detect remote execution based on:
  * __role == "client" (explicit client auth)
  * Remote master (not localhost/127.0.0.1/::1)
  * Missing IPC socket + existing client keys
- Use ClientEventSubscriber for remote execution
- Preserve IPC events for local execution (backwards compatible)

This complements the existing network event support in RemoteClient,
ensuring all three CLI tools (salt, salt-run, salt-key) can be run
fully remotely without requiring access to master IPC sockets.
The wheel function is `key.list_all_client` (singular `client`,
not `clients`); the plural form doesn't exist in
`salt/wheel/key.py`.  CI caught this on Photon 5 / AL2023 arm64 /
Photon 4 arm64 scenarios jobs with:

    salt.exceptions.CommandExecutionError: 'key.list_clients' is
    not available.

Switch both call sites in test_wheel_list_clients_through_proxy
and test_proxy_rotates_across_backends to the correct name.  The
response shape is still `{'clients': [...], 'clients_rejected':
[...], ...}`, which is what the assertion already expects.
ClearFuncs.wheel() dispatches to the wheel function via
``self.wheel_.call_func(fun, full_return=True, **clear_load)``.
When the request arrives through ``_is_client_bridge`` (AES
payload routed to ClearFuncs), ``clear_load`` still carries the
AES channel protocol fields ``id`` and ``ts``, plus
``client_id`` injected by RemoteWheelClient.master_call for the
pure-PKI auth path.  Spreading those into a wheel function with a
strict signature (e.g. ``def list_all_client():``) trips
``format_call`` with ``SaltInvocationError: 'client_id', 'ts'
and 'id' are invalid keyword arguments``.

Pop the three bridge fields unconditionally before the spread.
On the master-local path they are never present, so the pops are
no-ops.

CI caught this on Fedora 43 / AL 2023 arm64 / Photon 5 / Rocky 9
/ etc. scenarios jobs in run 41782156321 via
test_wheel_list_clients_through_proxy.
The async ``ClearFuncs.wheel`` method is shadowed by
``_sync_wheel`` whenever ``master_async_mworker`` is False,
which is the LTS default.  My prior commit added the client_id /
id / ts pop to the async ``wheel`` only, so in the default
LTS deployment the fix was never reached and CI still tripped
``SaltInvocationError: 'client_id', 'ts' and 'id' are invalid
keyword arguments for 'salt.loaded.int.wheel.key.list_all_client'``
in run 41827046805.

Apply the same pop in ``_sync_wheel`` so both dispatch paths
strip the bridge-protocol fields before spreading
``**clear_load`` into the wheel function.
twangboy
twangboy previously approved these changes Nov 4, 2026
dwoz added 2 commits November 4, 2026 15:04
The three remote-CLI scenario tests (haproxy / cluster / containers)
built their master, minion, and client configs without the
FIPS_TESTRUN overrides that the rest of the suite applies (see
tests/conftest.py and tests/pytests/integration/cluster/conftest.py).
Under ``FIPS_TESTRUN=1`` this made the client (and in cluster.py
the self-built masters) default to ``PKCS1v15-SHA1`` /
``OAEP-SHA1``, which the master then rejects at sign-in with
``SaltClientError: Attempt to authenticate with the salt master
failed`` because SHA1 is disallowed in FIPS mode.

Apply the same pattern the suite's FIPS fixtures use:
- masters: ``fips_mode`` + ``publish_signing_algorithm``
  (+ ``cluster_encryption_algorithm`` for cluster masters)
- minions / clients: ``fips_mode`` + ``signing_algorithm`` +
  ``encryption_algorithm``

Chose SHA224 under FIPS and SHA1 otherwise -- matches
tests/conftest.py and tests/pytests/integration/cluster/conftest.py.

Verified locally: Photon 4 CI container, ``FIPS_TESTRUN=1``,
``nox -e ci-test-onedir`` ->
TestRemoteCLIBehindClusterLB::test_wheel_list_clients_through_proxy
and TestRemoteCLIBehindClusterLB::test_proxy_rotates_across_backends
both PASS (``2 passed in 315.66s``).
…nts key

``ClientEventSubscriber._authenticate_pki`` already advertises the
client's ``encryption_algorithm`` in the auth payload so the
server wraps the per-session Crypticle key with a matching OAEP
hash.  On the unwrap side we were calling
``priv_key.decrypt(wrapped)`` with no ``algorithm=`` arg --
which defaults to ``OAEP-SHA1``.  Under FIPS the salt-side
``PrivateKey._enforce_fips`` rejects SHA1-based OAEP with
``UnsupportedAlgorithm: Algorithm OAEP-SHA1 uses SHA1 which is
not allowed in FIPS mode``, so ``test_remote_client_executes_
command_on_minion`` and ``test_remote_client_receives_events_
over_network`` failed on every Photon FIPS attempt of run
41922073231.

Read ``encryption_algorithm`` from opts (the same value we sent
as ``enc_algo`` above) and pass it into ``priv_key.decrypt``.
Fall through to ``OAEP-SHA1`` on non-FIPS hosts to preserve the
historical behavior.

Verified locally: Photon 4 CI container, ``FIPS_TESTRUN=1``,
onedir overlay with this fix ->
TestRemoteCommandExecution::test_remote_client_executes_command_on_minion
and TestRemoteCommandExecution::test_remote_client_receives_events_over_network
both PASS.

This branch was previously deployed

1 inactive deployment
ci — 01634cdb Deployed Nov 5, 2026 by dwoz via Build Onedir Packages / macOS (x86_64) #28461
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

test:full Run the full test suite

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants