Rotate Infrastructure Service Credentials 

Credential rotation is the regular replacement of the passwords and keys that an Oro application uses to connect to its infrastructure services. This guide explains how to rotate the credentials of PostgreSQL, Redis, Elasticsearch, MongoDB, and RabbitMQ without downtime. The procedure does not require code changes.

Hint

This guide applies to self-hosted Oro applications. If your application is hosted on OroCloud, the OroCloud team manages the credentials of the infrastructure services.

How Credential Rotation Works 

The Oro application reads the credentials from the data source names (DSNs) in environment variables or .env-app files. The application resolves these variables at runtime. The application cache, including the compiled service container, does not contain the credentials. For this reason, you do not need to clear or warm up the cache when you rotate the credentials.

Important

Do not set the credentials as default values of environment variables in the configuration files, for example, env(ORO_DB_PASSWORD): <password> in the config/parameters.yml file. The application compiles these default values into the cache. As a result, the cache files contain the credentials, and the old credentials remain in the cache files after the rotation.

Long-running processes connect to the services again while they work:

  • A message queue consumer closes its database connections after each message and opens new ones for the next message.

  • A message queue consumer can open a new connection to RabbitMQ while it processes messages.

  • The websocket server keeps persistent connections to the database and Redis.

As a result, every process must be able to authenticate at any moment.

Warning

Do not change the password of the only service user of a running application. Long-running processes connect with the old password and fail. For example, the consumer stops with the password authentication failed error from PostgreSQL or the ACCESS_REFUSED error from RabbitMQ. Create the new credentials first, and revoke the old credentials only after all processes use the new ones.

To rotate the credentials without downtime, keep two valid credentials for a short period. Each service supports one of the following options:

  • Two users with the same permissions — PostgreSQL, Elasticsearch, MongoDB, and RabbitMQ. The application uses the users in turn.

  • One user with two valid passwords — Redis. A Redis user can have several passwords at the same time.

Each service section below starts with a one-time preparation. Complete the preparation before the first rotation.

Rotation Procedure 

Perform the following steps for each service. To rotate the credentials of several services at once, complete step 1 for each service, steps 2 and 3 once, and then steps 4 and 5 for each service.

  1. Create the new credentials for the service. Keep the old credentials valid. For the commands, see the section of the service below.

  2. Update the connection strings of the application. See Update the Connection Strings.

  3. Restart the application processes. See Restart the Application Processes.

  4. Verify that no process connects to the service with the old credentials. For the commands, see the section of the service below.

  5. Disable or delete the old credentials.

Until step 5, you can roll back the rotation. To roll back, restore the old connection strings and repeat step 3. After step 5, perform a new rotation instead.

You can run the same procedure on a schedule or on demand. If the old credentials are compromised, you can perform step 5 right after step 3. In this case, the processes that do not use the new credentials yet fail. Restart these processes, and run the failed message queue jobs again.

The examples on this page pass passwords as command arguments. Other users of the server can see command arguments in the process list. Where the client supports it, enter the password at a prompt instead.

Update the Connection Strings 

The following environment variables contain the credentials of the infrastructure services:

Service

Environment variables

DSN format

PostgreSQL

ORO_DB_DSN. In the default .env-app file, ORO_DB_DSN refers to ORO_DB_URL.

postgres://<user>:<password>@<host>:5432/<database>?...

Redis

ORO_REDIS_CACHE_DSN, ORO_REDIS_DOCTRINE_DSN, ORO_REDIS_LAYOUT_DSN, and ORO_SESSION_DSN if the application stores sessions in Redis. In the default .env-app file, the cache variables refer to ORO_REDIS_URL.

redis://<user>:<password>@<host>:6379/<database>

Elasticsearch

ORO_SEARCH_ENGINE_DSN, ORO_WEBSITE_SEARCH_ENGINE_DSN. In the default .env-app file, these variables refer to ORO_SEARCH_URL.

https://<user>:<password>@<host>:9200/?prefix=<index prefix>

MongoDB

ORO_MONGODB_DSN_PUBLIC, ORO_MONGODB_DSN_PRIVATE. In the default .env-app file, these variables refer to ORO_MONGODB_SERVER.

mongodb://<user>:<password>@<host>:27017/<database>?authSource=admin

RabbitMQ

ORO_MQ_DSN

amqp://<user>:<password>@<host>:5672/<vhost>

Update every variable that contains the old credentials. For the full DSN syntax of each service, see Managing Application Configuration with .env-app Files and Real Environment Variables in Oro. To connect to the services over TLS, see Secure (TLS) Connections.

Important

Encode the user name and the password in a DSN with URL encoding (percent-encoding), for example, with the PHP rawurlencode() function. The characters @, :, /, ?, #, %, and + have a special meaning in a URL. If the password contains them and is not encoded, the application cannot parse the DSN or reads a different password. For example, a / character in the PostgreSQL password causes the Malformed parameter "url" error. The Elasticsearch and RabbitMQ connections read a + character as a space.

If you compiled the .env-app files with the composer dump-env prod command, the application reads the values from the .env-app.local.php file. The application ignores changes in the .env-app files while the .env-app.local.php file exists. Real environment variables still take precedence over the values in the .env-app.local.php file. If you keep the credentials in the .env-app files, update the files, and then compile them again. In the application root directory, run:

composer dump-env prod

Restart the Application Processes 

After you update the connection strings, restart the processes of the application in the following way:

Process

Action

PHP-FPM

Reload PHP-FPM, for example, with the systemctl reload php-fpm command. The reload replaces the PHP-FPM workers without stopping the service. The reload is required if the credentials come from real environment variables or from the .env-app.local.php file and OPcache does not check file timestamps (opcache.validate_timestamps=0).

Message queue consumers

Restart the consumers with your process manager. For example, if Supervisor runs the consumers as the oro_message_consumer program, run the supervisorctl restart oro_message_consumer:* command. On the SIGTERM signal, a consumer finishes the current message and exits. Make sure that the stop timeout of the process manager, such as the stopwaitsecs option of Supervisor, is longer than the processing time of your longest message. Otherwise, the process manager kills the consumer before the message is processed. For the consumer configuration, see Supervisord.

Websocket server

Restart the process that runs the gos:websocket:server command. The websocket server keeps persistent connections to the database and Redis. If you revoke the old database credentials and terminate these connections, the websocket server stops.

Cron

No action is required. Each run of the oro:cron command starts a new process.

Rotate PostgreSQL Credentials 

Prepare the Database for Rotation 

In PostgreSQL, the role that creates a database object becomes its owner. If the application connects as one role and later as another role, the second role cannot change the tables that the first role created. As a result, schema migrations fail. To avoid this, make a group role without the login permission the owner of all database objects. Then, make the login roles of the application members of this group role.

Perform the following steps once:

  1. Connect to the PostgreSQL server as a superuser, and create the roles:

    CREATE ROLE oro_owner NOLOGIN;
    GRANT oro_owner TO <current role>;
    CREATE ROLE oro_app_a LOGIN PASSWORD '<password>' IN ROLE oro_owner;
    ALTER ROLE oro_app_a SET role = 'oro_owner';
    CREATE ROLE oro_app_b NOLOGIN IN ROLE oro_owner;
    ALTER ROLE oro_app_b SET role = 'oro_owner';
    

    Replace the following placeholders:

    • <current role> — The role that the application uses now. The GRANT statement keeps the access of this role to the objects after their owner changes in the next step.

    • <password> — The password of the oro_app_a role.

    The ALTER ROLE ... SET role statement makes each new session of the login role act as the oro_owner role. As a result, the objects that the application creates belong to the oro_owner role.

  2. Connect to the database of the application as a superuser, and transfer the ownership of the existing objects to the oro_owner role:

    ALTER DATABASE <database> OWNER TO oro_owner;
    ALTER SCHEMA public OWNER TO oro_owner;
    DO $$
    DECLARE r record;
    BEGIN
      FOR r IN SELECT c.relname, c.relkind FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
               WHERE n.nspname = 'public' AND c.relkind IN ('r','v','m','S','p','f')
                 AND NOT (c.relkind = 'S' AND EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = c.oid AND d.deptype IN ('a','i')))
      LOOP
        EXECUTE format('ALTER %s public.%I OWNER TO oro_owner',
          CASE r.relkind WHEN 'S' THEN 'SEQUENCE' WHEN 'v' THEN 'VIEW' WHEN 'm' THEN 'MATERIALIZED VIEW'
                         WHEN 'f' THEN 'FOREIGN TABLE' ELSE 'TABLE' END, r.relname);
      END LOOP;
      FOR r IN SELECT p.oid::regprocedure AS sig, p.prokind FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
               WHERE n.nspname = 'public' AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = p.oid AND d.deptype = 'e')
      LOOP
        EXECUTE format('ALTER %s %s OWNER TO oro_owner',
          CASE r.prokind WHEN 'p' THEN 'PROCEDURE' WHEN 'a' THEN 'AGGREGATE' ELSE 'FUNCTION' END, r.sig);
      END LOOP;
    END $$;
    

    Replace <database> with the name of the application database. The script skips the sequences that belong to table columns and the functions that belong to extensions. These objects change their owner together with the table or the extension.

    The script does not change the owner of other object types, such as enum types and domains. The Oro application does not create these objects. If your customizations create them, change their owner to the oro_owner role manually.

    Note

    Do not use the REASSIGN OWNED BY statement for this step if the current application role owns other databases. The statement also transfers the ownership of these databases.

  3. Set the oro_app_a role and its password in the ORO_DB_DSN variable, and restart the application processes.

  4. When no session uses the previous application role, disable the login of this role. To check the sessions, use the query from the next section.

Rotate the Password 

In the following example, the application uses the oro_app_a role. In the next rotation, swap the roles.

  1. Enable the second role and set a new password for it:

    ALTER ROLE oro_app_b LOGIN PASSWORD '<new password>';
    

    Replace <new password> with the new password of the oro_app_b role.

  2. Set the oro_app_b role and its password in the ORO_DB_DSN variable, and restart the application processes.

  3. Verify that no session uses the old role. The following query must return no rows:

    SELECT pid, application_name, client_addr, backend_start, state
    FROM pg_stat_activity
    WHERE usename = 'oro_app_a';
    

    If the query returns rows, find the processes that use these sessions and restart them.

  4. Disable the old role, and terminate its remaining sessions:

    ALTER ROLE oro_app_a NOLOGIN PASSWORD NULL;
    SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'oro_app_a';
    

    The NOLOGIN option does not close the sessions that are already open. For this reason, the second statement terminates them.

For more information, see PostgreSQL ALTER ROLE.

Rotate Redis Credentials 

Prepare Redis for Rotation 

Redis 6.2 and later versions support several passwords for one user of the access control list (ACL). Use an ACL user instead of the requirepass setting.

In the ACL SETUSER command, the > prefix adds a password to the user, and the < prefix removes a password. The examples in this section keep the passwords in shell variables. Add the redis-cli options that your Redis server requires, such as -h and --user.

Perform the following steps once:

  1. To create the oro_app user with full access, set the REDIS_PASSWORD variable to the password of the user, and run:

    redis-cli ACL SETUSER oro_app on ">${REDIS_PASSWORD}" '~*' '&*' '+@all'
    
  2. Set the oro_app user and its password in the Redis connection strings, and restart the application processes.

  3. Verify that the application processes connect as the oro_app user. The user field of each connection shows its user:

    redis-cli CLIENT LIST
    
  4. When no application connection uses the default user, disable the default user:

    redis-cli ACL SETUSER default off
    

    Before you disable the default user, make sure that the replica nodes, Sentinel, and monitoring tools do not use it.

    After you disable the default user, the redis-cli command without credentials fails with the NOAUTH Authentication required error. For this reason, add the --user and --askpass options to the redis-cli commands in the next steps and rotations. For example:

    redis-cli --user oro_app --askpass CLIENT LIST
    

Redis keeps ACL changes in memory. To keep the changes after a restart, save them to the ACL file with the ACL SAVE command, or to the redis.conf file with the CONFIG REWRITE command. Save the changes after each step that changes the ACL. If Redis runs without an ACL file and without a configuration file, for example, in the default Redis Docker image, both commands fail, and Redis loses the ACL changes after a restart. For more information, see Redis ACL.

Rotate the Password 

  1. To add the new password to the user, set the NEW_REDIS_PASSWORD variable to the new password, and run the following command. The old password remains valid.

    redis-cli ACL SETUSER oro_app ">${NEW_REDIS_PASSWORD}"
    
  2. Set the new password in the Redis connection strings, and restart the application processes.

  3. Verify that no connection of the oro_app user is older than the restart. The age field shows the age of a connection in seconds:

    redis-cli CLIENT LIST | grep 'user=oro_app'
    
  4. To remove the old password, set the OLD_REDIS_PASSWORD variable to the old password, and run:

    redis-cli ACL SETUSER oro_app "<${OLD_REDIS_PASSWORD}"
    

The connections that are already authenticated continue to work after you remove the old password. The new connections with the old password fail.

Note

If Redis rejects the credentials of the cache connections, the application continues to work without the Redis cache. The application does not report the error to the user. After each rotation, check with the CLIENT LIST command that the application processes connect to Redis.

Warning

If the application stores sessions in Redis and Redis rejects the credentials, the requests fail. Complete step 3 before you remove the old password.

Redis with Replicas and Sentinel 

Redis does not replicate ACL changes. Run each ACL SETUSER command on the primary node and on every replica node.

If the replica nodes and Sentinel authenticate on the primary node with the application user, update their configuration in step 2, before you remove the old password:

  • masteruser and masterauth — The user and the password that a replica node uses to connect to the primary node.

  • sentinel auth-user and sentinel auth-pass — The user and the password that Sentinel uses to monitor the nodes.

If these settings still contain the old password after step 4, the replica nodes cannot connect to the primary node after they reconnect. As a result, the replicas stop receiving data. Sentinel cannot connect to the nodes either, and it cannot fail over to a replica. To avoid this dependency, use a separate ACL user for the replication and for Sentinel.

The Oro application does not authenticate on the Sentinel nodes. It authenticates only on the primary and replica nodes. Do not enable authentication on Sentinel. Otherwise, the application cannot get the address of the primary node from Sentinel. For more information, see Redis Sentinel.

Rotate Elasticsearch Credentials 

Prepare Elasticsearch for Rotation 

The application authenticates on Elasticsearch only if the security features of Elasticsearch are enabled (xpack.security.enabled: true). If the security features are disabled, enable them in a maintenance window. Enabling the security features requires a restart of the Elasticsearch nodes and a change of the connection strings at the same time.

Create a role for the application. The following role allows the application to manage and use its own indices. In this example, the indices of the application start with the default oro_search and oro_website_search prefixes:

curl -u elastic -X PUT 'https://<host>:9200/_security/role/oro_app' \
     -H 'Content-Type: application/json' \
     -d '{"cluster": ["monitor"], "indices": [{"names": ["oro_search*", "oro_website_search*"], "privileges": ["create_index", "delete_index", "manage", "read", "write", "view_index_metadata"]}]}'

Replace <host> with the host name of the Elasticsearch server. If your application uses other index prefixes, change the index names in the role. For the list of privileges, see Elasticsearch security privileges.

The application uses two users with this role in turn. Create the first user, for example, oro_app_a, and set it in the Elasticsearch connection strings.

Rotate the Password 

In the following example, the application uses the oro_app_a user. In the next rotation, swap the users.

  1. Create or update the second user. The request sets the new password and the role, and enables the user if a previous rotation disabled it:

    curl -u elastic -X POST 'https://<host>:9200/_security/user/oro_app_b' \
         -H 'Content-Type: application/json' \
         -d '{"password": "<new password>", "roles": ["oro_app"], "enabled": true}'
    

    Replace <new password> with the new password of the oro_app_b user. The password must be at least 6 characters long.

  2. Set the oro_app_b user and its password in the Elasticsearch connection strings, and restart the application processes.

  3. Verify that no process uses the old user. Elasticsearch does not list the connections of a user. Make sure that you restarted all PHP-FPM pools, consumers, and websocket servers after the switch. If your license includes security audit logging, check the authentication events of the old user.

  4. Disable the old user:

    curl -u elastic -X PUT 'https://<host>:9200/_security/user/oro_app_a/_disable'
    

Elasticsearch checks the credentials in every request. A process that still uses the old user receives the 401 Unauthorized response immediately. For example, a consumer that was not restarted fails the current reindexation job. For this reason, disable the old user instead of deleting it. To restore access, enable the user with the PUT _security/user/oro_app_a/_enable request. For more information, see Elasticsearch user API.

Rotate MongoDB Credentials 

Prepare MongoDB for Rotation 

The application uses two users with the same roles in turn. The users need the readWrite role in the databases that store the public and private files. For example, to create the first user in the admin database, run the following command in the MongoDB Shell:

db.getSiblingDB('admin').createUser({
    user: 'oro_app_a',
    pwd: '<password>',
    roles: [{role: 'readWrite', db: 'media'}, {role: 'readWrite', db: 'private'}]
})

Replace the following values:

  • <password> — The password of the user.

  • media and private — The database names from the ORO_MONGODB_DSN_PUBLIC and ORO_MONGODB_DSN_PRIVATE variables.

If you create the users in the admin database, add the authSource=admin option to the connection strings. For more information, see MongoDB createUser.

Rotate the Password 

In the following example, the application uses the oro_app_a user. In the next rotation, swap the users.

  1. Create the second user, oro_app_b, with a new password and the same roles as in the previous example.

  2. Set the oro_app_b user and its password in the MongoDB connection strings, and restart the application processes.

  3. Verify that no connection uses the old user. The following command must return no operations:

    db.getSiblingDB('admin').aggregate([
        {$currentOp: {allUsers: true, idleConnections: true}},
        {$match: {'effectiveUsers.user': 'oro_app_a'}}
    ])
    
  4. Delete the old user:

    db.getSiblingDB('admin').dropUser('oro_app_a')
    

After you delete the user, the connections that are already open fail with the Unauthorized error. For this reason, complete step 3 before you delete the user.

Rotate RabbitMQ Credentials 

Prepare RabbitMQ for Rotation 

The application uses two users with the same permissions in turn. The first user is the user that the application uses now.

The application user does not need user tags. However, the first user can be the only administrator of RabbitMQ. For example, the RabbitMQ Docker image creates the user from the RABBITMQ_DEFAULT_USER variable with the administrator tag. To check the tags of the users, run:

rabbitmqctl list_users

Warning

The rotation deletes the old user. If the application user is the only user with the administrator tag, RabbitMQ has no administrator after the first rotation. As a result, nobody can sign in to the management UI if the management plugin is enabled. Before the first rotation, create a separate administrator user for RabbitMQ.

Rotate the Password 

In the following example, the application uses the oro_mq_a user. In the next rotation, swap the users.

  1. Create the second user, and grant it the same permissions as the first user:

    rabbitmqctl add_user oro_mq_b '<new password>'
    rabbitmqctl set_permissions -p <vhost> oro_mq_b '.*' '.*' '.*'
    

    Replace the following placeholders:

    • <new password> — The password of the oro_mq_b user.

    • <vhost> — The virtual host of the application, for example, /.

    If the first user has narrower permissions, grant the same permissions to the second user.

  2. Set the oro_mq_b user and its password in the ORO_MQ_DSN variable, and restart the application processes.

  3. Verify that the old user has no connections. The output of the following command must not contain the oro_mq_a user:

    rabbitmqctl list_connections user name
    
  4. Delete the old user:

    rabbitmqctl delete_user oro_mq_a
    

For more information, see RabbitMQ access control.

Related Topics