Skip to content

feat(spider-storage)!: Read database credentials via environment variables.#397

Merged
LinZhihao-723 merged 6 commits into
y-scope:mainfrom
20001020ycx:feat/2026-07-14-storage-db-password-env
Jul 15, 2026
Merged

feat(spider-storage)!: Read database credentials via environment variables.#397
LinZhihao-723 merged 6 commits into
y-scope:mainfrom
20001020ycx:feat/2026-07-14-storage-db-password-env

Conversation

@20001020ycx

@20001020ycx 20001020ycx commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Description

This PR extends how database credentials are passed from storage to the database: the username and password can now be supplied through environment variables, not just the config file — addressing the concern of storing them in plaintext (e.g. in a Kubernetes ConfigMap).

Credentials are read from the config file's credentials block when present, and from the environment variables when the block is omitted. We carefully enumerate all possible scenarios and define their behavior:

  • config and env both set → config (config takes precedence; env is ignored)
  • env only → env
  • config only → config
  • neither → startup fails with a "required environment variable … is not set" error

Note

BREAKING CHANGE:
Username and password are optional in config rather mandatory.

Checklist

  • The PR satisfies the contribution guidelines.
  • This is a breaking change and that has been indicated in the PR title.
  • Necessary docs have been updated, OR no docs need to be updated.

Validation performed

Added a unit test covering two scenarios: it reads both variables, and it errors when one is unset.

All CI passes

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Added typed, environment-based database credential handling with dedicated env vars and a unified credentials field.
    • Publicly exposed credential types and a clear error for missing environment variables.
  • Bug Fixes

    • MariaDB connections now consistently use the configured grouped credentials.
  • Tests

    • Updated/extended tests to validate environment loading and missing-variable failures.
  • Chores

    • Renamed/wired test-task environment variables to use the new credential env var names.

@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: dae130cf-fb3a-43e3-9281-4a349a019ae7

📥 Commits

Reviewing files that changed from the base of the PR and between 411665a and 6113e38.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (1)
  • components/spider-storage/src/config.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • components/spider-storage/src/config.rs

Walkthrough

Changes

Database configuration now uses nested credentials loaded from SPIDER_STORAGE_DB_USERNAME and SPIDER_STORAGE_DB_PASSWORD, with typed missing-variable errors and Serde fallback handling. MariaDB connections, infrastructure tests, and Huntsman task wiring use the updated credential contract.

Database credential loading

Layer / File(s) Summary
Credential contract and validation
components/spider-storage/src/config.rs, components/spider-storage/src/lib.rs, components/spider-storage/Cargo.toml
Adds nested credential types, environment-variable loading, typed errors, public exports, Serde fallback behaviour, a development test dependency, and unit tests.
MariaDB connection integration
components/spider-storage/src/db/mariadb.rs, components/spider-storage/tests/mariadb_infra.rs
Uses nested credentials for MariaDB authentication and updates infrastructure configuration construction and documentation.
Test-task credential wiring
taskfiles/test.yaml
Renames and forwards the new database credential environment variables through Huntsman tasks.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant TestTask
  participant DatabaseConfig
  participant DatabaseCredentials
  participant MariaDbStorageConnector
  TestTask->>DatabaseConfig: deserialize configuration
  DatabaseConfig->>DatabaseCredentials: resolve credentials
  DatabaseCredentials-->>DatabaseConfig: username and password
  DatabaseConfig->>MariaDbStorageConnector: provide credentials
  MariaDbStorageConnector->>MariaDbStorageConnector: configure MySQL authentication
Loading

Suggested reviewers: sitaowang1998

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: spider-storage now reads database credentials from environment variables.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 unit tests (beta)
  • Create PR with unit tests

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.

@20001020ycx 20001020ycx changed the title feat(spider-storage)!: Read database credentials from the environment. feat(spider-storage)!: Read database credentials via the environment variables. Jul 14, 2026
@20001020ycx 20001020ycx force-pushed the feat/2026-07-14-storage-db-password-env branch from 0c16a54 to ff83d3d Compare July 14, 2026 19:01
@20001020ycx 20001020ycx marked this pull request as ready for review July 14, 2026 19:02
@20001020ycx 20001020ycx requested review from a team and sitaowang1998 as code owners July 14, 2026 19:02

@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.

🧹 Nitpick comments (1)
components/spider-storage/src/config.rs (1)

38-77: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider deriving Default for DatabaseCredentials.

Since String and secrecy::SecretString both implement the Default trait, you can simplify the code by deriving Default automatically and removing the manual implementation block.

♻️ Proposed refactor
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, Default)]
 pub struct DatabaseCredentials {
     pub username: String,
     pub password: SecretString,
 }
 
 impl DatabaseCredentials {
     /// Reads the database credentials from the [`DB_USERNAME_ENV`] and [`DB_PASSWORD_ENV`]
     /// environment variables.
     ///
     /// # Returns
     ///
     /// The credentials on success.
     ///
     /// # Errors
     ///
     /// Returns an error if:
     ///
     /// * [`CredentialsError::MissingEnvVar`] if either environment variable is unset.
     pub fn from_env() -> Result<Self, CredentialsError> {
         let username = std::env::var(DB_USERNAME_ENV)
             .map_err(|_| CredentialsError::MissingEnvVar(DB_USERNAME_ENV))?;
         let password = std::env::var(DB_PASSWORD_ENV)
             .map_err(|_| CredentialsError::MissingEnvVar(DB_PASSWORD_ENV))?;
         Ok(Self {
             username,
             password: SecretString::from(password),
         })
     }
 }
-
-impl Default for DatabaseCredentials {
-    fn default() -> Self {
-        Self {
-            username: String::new(),
-            password: SecretString::from(String::new()),
-        }
-    }
-}
🤖 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 `@components/spider-storage/src/config.rs` around lines 38 - 77, Derive Default
on DatabaseCredentials alongside its existing Clone and Debug derives, then
remove the manual impl Default for DatabaseCredentials block. Preserve from_env
and all field types unchanged.
🤖 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.

Nitpick comments:
In `@components/spider-storage/src/config.rs`:
- Around line 38-77: Derive Default on DatabaseCredentials alongside its
existing Clone and Debug derives, then remove the manual impl Default for
DatabaseCredentials block. Preserve from_env and all field types unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 57b10cc5-b7ec-48ee-8acd-c54e2a8382a0

📥 Commits

Reviewing files that changed from the base of the PR and between 1fe99d6 and ff83d3d.

📒 Files selected for processing (5)
  • components/spider-storage/src/bin/grpc_server.rs
  • components/spider-storage/src/config.rs
  • components/spider-storage/src/db/mariadb.rs
  • components/spider-storage/src/lib.rs
  • components/spider-storage/tests/mariadb_infra.rs

Storage read the database username and password from its config file, which the
Helm chart renders into a Kubernetes ConfigMap -- leaving the password in
plaintext. It now reads them from the `SPIDER_STORAGE_DB_USERNAME` and
`SPIDER_STORAGE_DB_PASSWORD` environment variables (both required) via a
dedicated `DatabaseCredentials` type, so they can instead be injected from a
Secret and kept out of the ConfigMap.

BREAKING CHANGE: the storage service now requires the database credentials to be
provided via environment variables; they are no longer read from the config file.
@20001020ycx 20001020ycx force-pushed the feat/2026-07-14-storage-db-password-env branch from ff83d3d to d4e4473 Compare July 14, 2026 19:31

@LinZhihao-723 LinZhihao-723 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Updated to make use of serde to implement the following behavior:

  • The credentails can be explicitly given in the config, but it is optional.
  • When it's optional, the config is read from the environment variable.
    • No need to explicitly read from env. This is automatically resolved by serde.

@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 `@components/spider-storage/src/config.rs`:
- Around line 34-115: Update DatabaseConfig deserialization to pass an absent
credentials field through DatabaseCredentials::try_from, rather than requiring
the field before that conversion runs. Use a raw intermediate configuration or
equivalent with credentials represented as optional, ensuring both omitted and
null values fall back to DatabaseCredentials::from_env while explicitly provided
credentials remain unchanged.

In `@taskfiles/test.yaml`:
- Around line 220-231: Wrap the long vars list in the requires block across
multiple lines while preserving all four required variable names and the
existing YAML structure.
🪄 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: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: c053c20e-48eb-42ea-a00b-36f65715095a

📥 Commits

Reviewing files that changed from the base of the PR and between ff83d3d and ad72fc3.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • components/spider-storage/Cargo.toml
  • components/spider-storage/src/config.rs
  • components/spider-storage/src/db/mariadb.rs
  • components/spider-storage/src/lib.rs
  • components/spider-storage/tests/mariadb_infra.rs
  • taskfiles/test.yaml
🚧 Files skipped from review as they are similar to previous changes (2)
  • components/spider-storage/tests/mariadb_infra.rs
  • components/spider-storage/src/db/mariadb.rs

Comment thread components/spider-storage/src/config.rs
Comment thread taskfiles/test.yaml Outdated

@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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
components/spider-storage/src/config.rs (1)

106-114: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Contradiction with PR objective regarding configuration file support.

Based on the PR objectives, providing credentials through the configuration file is no longer supported. However, this try_from implementation explicitly processes provided credentials via Some(RawCredentials { ... }), and the test credentials_come_from_config_when_present at line 130 verifies this functionality.

If configuration-based credentials are truly meant to be unsupported, consider removing the Some branch, marking the credentials field with #[serde(skip)], and relying entirely on from_env(). Otherwise, the PR objective might need an update to reflect that config-based overrides are still permitted.

🤖 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 `@components/spider-storage/src/config.rs` around lines 106 - 114, Remove
configuration-file credential handling from TryFrom for the credentials type by
eliminating the Some(RawCredentials { ... }) path and always using from_env().
Mark the credentials field with #[serde(skip)] and update or remove
credentials_come_from_config_when_present so tests no longer expect
configuration-based overrides.
🤖 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 `@components/spider-storage/src/config.rs`:
- Around line 147-165: Update credentials_resolve_from_env_when_omitted and the
underlying DatabaseCredentials resolver to use an injectable environment source
instead of std::env::set_var/remove_var. Keep the test’s both-set and
missing-variable assertions, while avoiding process-wide environment mutation;
do not rely on making the entire test binary single-threaded unless that is the
established project-wide approach.

---

Outside diff comments:
In `@components/spider-storage/src/config.rs`:
- Around line 106-114: Remove configuration-file credential handling from
TryFrom for the credentials type by eliminating the Some(RawCredentials { ... })
path and always using from_env(). Mark the credentials field with #[serde(skip)]
and update or remove credentials_come_from_config_when_present so tests no
longer expect configuration-based overrides.
🪄 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: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 7f2c925c-951c-41aa-b83b-28f0363095ee

📥 Commits

Reviewing files that changed from the base of the PR and between ad72fc3 and 411665a.

📒 Files selected for processing (2)
  • components/spider-storage/src/config.rs
  • taskfiles/test.yaml
🚧 Files skipped from review as they are similar to previous changes (1)
  • taskfiles/test.yaml

Comment thread components/spider-storage/src/config.rs Outdated
…ightly clippy ICE.

`#[test]` followed by a proc-macro attribute (`#[serial]`) trips a nightly rustc
ICE (`attribute is missing tokens ... rustc_test_entrypoint_marker`) when compiling
the lib-test target, failing `lint-rust`. Expanding `#[serial]` before the built-in
`#[test]` marker exists avoids it, leaving the tests otherwise unchanged.
@20001020ycx 20001020ycx changed the title feat(spider-storage)!: Read database credentials via the environment variables. feat(spider-storage): Read database credentials via the environment variables. Jul 14, 2026
@20001020ycx 20001020ycx force-pushed the feat/2026-07-14-storage-db-password-env branch from 411665a to 5c30201 Compare July 14, 2026 23:45
Comment on lines +47 to +56
/// The credentials used to connect to the database.
///
/// By default, Spider expects the database credentials to be supplied through the following
/// environment variables:
///
/// * Database username: `SPIDER_STORAGE_DB_USERNAME`
/// * Database password: `SPIDER_STORAGE_DB_PASSWORD`
///
/// These can be overridden by explicitly supplying the `credentials` field in the
/// configuration file.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Updated for clarity.

@20001020ycx 20001020ycx changed the title feat(spider-storage): Read database credentials via the environment variables. feat(spider-storage)!: Read database credentials via the environment variables. Jul 15, 2026
@LinZhihao-723 LinZhihao-723 changed the title feat(spider-storage)!: Read database credentials via the environment variables. feat(spider-storage)!: Read database credentials via environment variables. Jul 15, 2026
@LinZhihao-723 LinZhihao-723 merged commit 86cf7a2 into y-scope:main Jul 15, 2026
17 checks passed
20001020ycx added a commit to 20001020ycx/spider that referenced this pull request Jul 15, 2026
…ironment variables.

Stop rendering the database username/password into the storage ConfigMap.
Storage now reads them from `SPIDER_STORAGE_DB_USERNAME`/`SPIDER_STORAGE_DB_PASSWORD`
(spider-storage y-scope#397), injected via `secretKeyRef` from the database Secret. The
Secret now renders in both bundled and external modes (`root_password` stays
bundled-only) so the credentials are available regardless of deployment mode.
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