Skip to content

fix: validate the env variables on startup - #140

Merged
AnonymousXC merged 2 commits into
devfrom
fix/validate-envirnoment-variables
Nov 26, 2026
Merged

AnonymousXC merged 2 commits into
devfrom
fix/validate-envirnoment-variables

Conversation

@AnonymousXC

@AnonymousXC AnonymousXC commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

closes #103

Summary by Sourcery

Validate Krini configuration during startup so deployment errors are reported immediately and invalid settings cannot cause misleading runtime behavior.

Bug Fixes:

  • Validate required and optional environment variables at startup, refusing to launch on fatal configuration errors and safely ignoring invalid access-request URLs.

Enhancements:

  • Add structured validation and logging for application origins, registry URLs, OIDC callback URLs, and login provider configurations, including secret-safe provider diagnostics and non-fatal operational warnings.

Documentation:

  • Update operator and login documentation to describe startup validation, fatal configuration errors, warnings, and URL constraints.

Tests:

  • Add comprehensive settings validation and startup enforcement tests, including invalid configuration handling and safe access-request URL behavior.

@AnonymousXC
AnonymousXC requested a review from uniqueg as a code owner November 26, 2026 05:48
@sourcery-ai

sourcery-ai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Implement startup validation for required settings and provider entries, report warnings without secrets, and expose only valid compute-access URLs.

  • src/lib/settings.ts L1-268

Run settings enforcement during Node.js startup so fatal configuration errors prevent the server from starting.

  • src/instrumentation.ts L1-6

Use the validated compute-access URL in the user-info response instead of returning the environment value directly.

  • src/app/auth/api/user-info/route.ts L10, L53

Configuration

Supply minimal valid settings to the image smoke-test container so startup validation passes.

  • scripts/check-image.sh L6, L22-30, L45

Documentation

Document startup validation requirements, fatal errors, warnings, and the registry URL constraint for operators.

  • docs/operator-guide/configuration.md L20, L35-47

Explain how invalid login-provider entries are reported and when they prevent startup.

  • docs/operator-guide/login.md L64-68

Tests

Test settings validation, warning and fatal behavior, secret-safe reporting, startup enforcement, and omission of invalid access-request URLs.

  • src/app/auth/api/user-info/route.test.ts L70-78
  • src/lib/settings.test.ts L1-399

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (429ed0c) to head (670bb7b).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #140   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           27        28    +1     
  Lines          765       856   +91     
  Branches       207       233   +26     
=========================================
+ Hits           765       856   +91     

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

@read-the-docs-community

read-the-docs-community Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 krini | 🛠️ Build #36180369 | 📁 Comparing 670bb7b against latest (429ed0c)

  🔍 Preview build  

2 files changed
± operator-guide/configuration/index.html
± operator-guide/login/index.html

@sourcery-ai

sourcery-ai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 670bb7b

#103 fix: check the settings when Krini starts · 5 of 6 met

# Requirement Status Notes
1 At startup, validate LOGIN_PROVIDERS and report invalid entries by provider id and missing field without logging secrets; refuse to start if there is no valid provider. ✅ Met Startup enforcement logs provider problems and exits when none is usable; tests cover invalid entries, duplicate ids, missing fields, and secret-safe reporting.
2 Validate APP_ORIGIN as an http(s) origin. 🟡 Partly met The validator checks the scheme but accepts URLs with a path, query, or fragment, even though APP_ORIGIN is required to be an origin.
3 Validate CLOUD_REGISTRY_URL and ensure OIDC_REDIRECT_URI is on the same origin as APP_ORIGIN. ✅ Met The validator checks the registry URL and, when the optional redirect URI is configured, checks its scheme, origin, and callback path.
4 Validate COMPUTE_ACCESS_REQUEST_URL. ✅ Met Invalid values produce a warning and are omitted from the user-info response.
5 Warn if no provider has computeGroups or adminGroups. ✅ Met The validator emits this warning when usable providers have neither group configuration.
6 Refuse to start when required settings are missing and identify the problem; cover checks with unit tests and update the operator and login docs. ✅ Met Fatal problems are logged before startup is refused; tests exercise validation and enforcement, and both documents describe the behavior.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 9 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/lib/settings.ts" line_range="189-191" />
<code_context>
+    it("warns on an invalid COMPUTE_ACCESS_REQUEST_URL", () => {
+        setUp({ COMPUTE_ACCESS_REQUEST_URL: "not a url" });
+        expect(validateSettings().warnings).toContainEqual({
+            setting: "COMPUTE_ACCESS_REQUEST_URL",
+            problem: "is not a valid http(s) URL; the link is ignored",
+        });
+    });
+
</code_context>
<issue_to_address>
**Invalid links remain clickable**

When `COMPUTE_ACCESS_REQUEST_URL` is set to a non-HTTP(S) value, `validateSettings()` logs a warning, but `/auth/api/user-info` still returns the raw value and the UI renders it as an `href`; users see a link the warning says is ignored, and clicking a `javascript:` value executes script in their browser.

Suppress invalid `COMPUTE_ACCESS_REQUEST_URL` values in `/auth/api/user-info` so the UI does not render them as links.
</issue_to_address>

### Comment 2
<location path="src/lib/settings.ts" line_range="106" />
<code_context>
+            if (typeof value !== "string" || value === "") {
+                problems.push({
+                    setting: "LOGIN_PROVIDERS",
+                    problem: `${where} has no ${field}`,
+                });
+            }
</code_context>
<issue_to_address>
**Usable providers block startup**

When `LOGIN_PROVIDERS` contains a usable provider plus an incomplete or duplicate entry, `loginProviderProblems()` adds the incomplete or duplicate entry to `fatal`, so `enforceSettings()` exits even though `getLoginProviders()` keeps a usable provider; the deployment refuses to start.

Make incomplete and duplicate entries non-fatal when `getLoginProviders()` has a usable provider.

Also at `src/lib/settings.ts:113-117`, `src/lib/settings.ts:221-226`.
</issue_to_address>

### Comment 3
<location path="src/lib/settings.ts" line_range="103" />
<code_context>
+        const record = entry as Record<string, unknown>;
+        for (const field of REQUIRED_PROVIDER_FIELDS) {
+            const value = record[field];
+            if (typeof value !== "string" || value === "") {
+                problems.push({
+                    setting: "LOGIN_PROVIDERS",
</code_context>
<issue_to_address>
**Malformed issuer delays login failure**

When a provider has a non-empty but malformed `issuer` value, `loginProviderProblems()` accepts the issuer, so startup proceeds; `getEndpoints()` then fails to fetch its discovery document when the user signs in, and login fails without a startup diagnostic.

Validate that each provider’s `issuer` is a usable HTTP(S) URL before accepting the provider.
</issue_to_address>

### Comment 4
<location path="src/lib/settings.ts" line_range="168-170" />
<code_context>
+            const callback = new URL(redirectUri);
+            const app = appOrigin ? new URL(appOrigin) : null;
+            if (
+                (callback.protocol !== "http:" &&
+                    callback.protocol !== "https:") ||
+                (app && callback.origin !== app.origin)
+            ) {
+                fatal.push({
</code_context>
<issue_to_address>
**Wrong callback path breaks login**

When `OIDC_REDIRECT_URI` is an HTTP(S) URL on the `APP_ORIGIN` origin but its path is not `/auth/api/callback`, `validateSettings()` checks the scheme and origin but not the path, so the URI passes validation and is sent to the identity provider; the provider returns users to a route without the callback handler, and login fails.

Reject `OIDC_REDIRECT_URI` values whose path is not `/auth/api/callback`.

Also at `src/lib/settings.ts:172-176`.
</issue_to_address>

### Comment 5
<location path="src/lib/settings.ts" line_range="143" />
<code_context>
+    if (!appOrigin) {
+        fatal.push({ setting: "APP_ORIGIN", problem: "is not set" });
+    } else if (!isHttpUrl(appOrigin)) {
+        fatal.push({
+            setting: "APP_ORIGIN",
+            problem: "is not a valid http(s) URL",
</code_context>
<issue_to_address>
**HTTP production origin passes validation**

When `NODE_ENV` is production and `APP_ORIGIN` uses HTTP for a non-local host, `validateSettings` accepts a non-local HTTP `APP_ORIGIN` in production, so the server starts with an origin where browsers will not send its Secure session cookies and login sessions fail.

Reject non-HTTPS production origins except localhost during startup.
</issue_to_address>

### Comment 6
<location path="src/lib/settings.ts" line_range="28-31" />
<code_context>
+    "clientSecret",
+] as const;
+
+function isHttpUrl(value: string): boolean {
+    try {
+        const url = new URL(value);
+        return url.protocol === "http:" || url.protocol === "https:";
+    } catch {
+        return false;
</code_context>
<issue_to_address>
**Configured origin path is discarded**

When `APP_ORIGIN` is an HTTP(S) URL with a non-root path or query, `isHttpUrl()` accepts the value, so startup proceeds; `getAppOrigin()` reduces it to the URL origin and drops the configured path, leaving redirects and callback URLs without the configured prefix.

Validate that `APP_ORIGIN` is an origin with no path or query, rather than accepting any HTTP(S) URL.

Also at `src/lib/settings.ts:142-147`.
</issue_to_address>

### Comment 7
<location path="src/lib/settings.ts" line_range="156" />
<code_context>
+    if (!appOrigin) {
+        fatal.push({ setting: "APP_ORIGIN", problem: "is not set" });
+    } else if (!isHttpUrl(appOrigin)) {
+        fatal.push({
+            setting: "APP_ORIGIN",
+            problem: "is not a valid http(s) URL",
</code_context>
<issue_to_address>
**Registry requests target wrong endpoint**

When `CLOUD_REGISTRY_URL` includes a query or fragment, `isHttpUrl()` accepts the value, but `load` appends `/services` to the raw string, so the request targets the wrong endpoint and registry loading fails after startup.

Reject `CLOUD_REGISTRY_URL` values with a query or fragment before `load` appends `/services`.
</issue_to_address>

### Comment 8
<location path="docs/operator-guide/configuration.md" line_range="37" />
<code_context>
-through [Checking a deployment](deployment.md#checking-a-deployment).
+Krini checks its settings when it starts (see `src/lib/settings.ts`):
+a missing or invalid required setting (`LOGIN_PROVIDERS`, `APP_ORIGIN`,
+`CLOUD_REGISTRY_URL`, `OIDC_REDIRECT_URI`) is logged with the reason and
+Krini refuses to start. Warnings — an invalid `COMPUTE_ACCESS_REQUEST_URL`,
+or no provider with `computeGroups`/`adminGroups` — are logged but don't
</code_context>
<issue_to_address>
**Guide marks optional setting required**

When an operator relies on the startup-validation paragraph to determine whether `OIDC_REDIRECT_URI` must be set, the guide says a missing `OIDC_REDIRECT_URI` prevents startup, but validation skips the unset value and `getRedirectUri()` supplies a default from `APP_ORIGIN`; operators are told startup will fail when it succeeds.

Update the guide to explain that `OIDC_REDIRECT_URI` is optional and defaults from `APP_ORIGIN`.
</issue_to_address>

### Comment 9
<location path="src/lib/settings.test.ts" line_range="41-42" />
<code_context>
+        expect(validateSettings().fatal.length).toBeGreaterThan(0);
+    });
+
+    it("names each invalid provider entry and its missing field", () => {
+        setUp({
+            LOGIN_PROVIDERS: JSON.stringify([
+                { id: "broken", issuer: "https://i.example.org" },
</code_context>
<issue_to_address>
**Test missing issuer**

The issue asks for tests covering each check, but the provider tests do not cover an entry missing issuer. Add a case that checks the reported problem for that missing field.
</issue_to_address>

Sourcery assessment

Approval pending. 7 findings to address first.

Blocking findings: src/lib/settings.ts:191, src/lib/settings.ts:106, src/lib/settings.ts:103, src/lib/settings.ts:170, src/lib/settings.ts:143, and 2 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/lib/settings.ts Resolved
Comment thread src/lib/settings.ts Resolved
Comment thread src/lib/settings.ts Resolved
Comment thread src/lib/settings.ts Resolved
Comment thread src/lib/settings.ts Resolved
Comment thread src/lib/settings.ts Resolved
Comment thread src/lib/settings.ts Resolved
Comment thread docs/operator-guide/configuration.md Resolved
Comment thread src/lib/settings.test.ts Resolved

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

New gaps against the linked issues

Comment thread src/lib/settings.ts Resolved
@AnonymousXC
AnonymousXC merged commit e6f47c5 into dev Nov 26, 2026
42 checks passed
@AnonymousXC
AnonymousXC deleted the fix/validate-envirnoment-variables branch November 26, 2026 06:14
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.

fix: check the settings when Krini starts

1 participant