Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

feat: Microsoft and Okta sign-in with instance admin area (#1896)

Aman Agarwal5edb5450efa6
diff --git a/docker-compose.yml b/docker-compose.yml
index afec9f6f..f34fbb05 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -74,6 +74,12 @@ services:
GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET:-}
GITHUB_CLIENT_ID: ${GITHUB_CLIENT_ID:-}
GITHUB_CLIENT_SECRET: ${GITHUB_CLIENT_SECRET:-}
+ AZURE_AD_CLIENT_ID: ${AZURE_AD_CLIENT_ID:-}
+ AZURE_AD_CLIENT_SECRET: ${AZURE_AD_CLIENT_SECRET:-}
+ AZURE_AD_TENANT_ID: ${AZURE_AD_TENANT_ID:-}
+ OKTA_CLIENT_ID: ${OKTA_CLIENT_ID:-}
+ OKTA_CLIENT_SECRET: ${OKTA_CLIENT_SECRET:-}
+ OKTA_ISSUER: ${OKTA_ISSUER:-}
env_file:
- path: .env
diff --git a/docs/docs.json b/docs/docs.json
index ef75a63d..440f5f69 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -87,6 +87,7 @@
"latest/openlit/enterprise",
"latest/openlit/rbac",
"latest/openlit/audit-logs",
+ "latest/openlit/instance-admin",
"latest/openlit/alerts",
"latest/openlit/gpus"
]
diff --git a/docs/images/enterprise/instance-admin-admins.png b/docs/images/enterprise/instance-admin-admins.png
new file mode 100644
index 00000000..0bd52267
Binary files /dev/null and b/docs/images/enterprise/instance-admin-admins.png differ
diff --git a/docs/images/enterprise/instance-admin-auth.png b/docs/images/enterprise/instance-admin-auth.png
new file mode 100644
index 00000000..9e4cd33f
Binary files /dev/null and b/docs/images/enterprise/instance-admin-auth.png differ
diff --git a/docs/images/enterprise/instance-admin-settings-entry.png b/docs/images/enterprise/instance-admin-settings-entry.png
new file mode 100644
index 00000000..6ee90c9f
Binary files /dev/null and b/docs/images/enterprise/instance-admin-settings-entry.png differ
diff --git a/docs/images/organisation/database-config-list.png b/docs/images/organisation/database-config-list.png
new file mode 100644
index 00000000..9448642a
Binary files /dev/null and b/docs/images/organisation/database-config-list.png differ
diff --git a/docs/images/organisation/projects-list.png b/docs/images/organisation/projects-list.png
new file mode 100644
index 00000000..6d33e334
Binary files /dev/null and b/docs/images/organisation/projects-list.png differ
diff --git a/docs/latest/openlit/audit-logs.mdx b/docs/latest/openlit/audit-logs.mdx
index c1f16ac0..6f0c7ab2 100644
--- a/docs/latest/openlit/audit-logs.mdx
+++ b/docs/latest/openlit/audit-logs.mdx
@@ -74,6 +74,7 @@ OpenLIT records an event when a privileged request **succeeds**. Failed or denie
| Members and invitations | `member.invited`, `member.invitation_cancelled`, `member.invitation_declined`, `member.invitation_accepted`, `member.role_changed`, `member.permissions_updated`, `member.project_access_updated`, `member.ownership_transferred`, `member.removed` |
| Roles | `role.created`, `role.updated`, `role.deleted` |
| Licenses and entitlements | `license.applied`, `license.revoked`, `entitlement.granted`, `entitlement.revoked` |
+| Instance admin¹ | `instance_auth.updated`, `instance_admin.added`, `instance_admin.removed` |
| Projects | `project.created`, `project.updated`, `project.deleted`, `project.selected`, `project.environment_created` |
| Database configs | `db_config.created`, `db_config.updated`, `db_config.deleted`, `db_config.selected`, `db_config.shared` |
| API keys | `api_key.created`, `api_key.deleted`, `api_key.access_updated` |
@@ -93,6 +94,8 @@ OpenLIT records an event when a privileged request **succeeds**. Failed or denie
| GPUs | `gpu.price_created`, `gpu.price_updated`, `gpu.price_deleted`, `gpu.recommendation_dismissed`, `gpu.recommendation_reopened` |
| Governance | `governance.report_viewed`, `governance.passport_exported` |
+¹ [Instance admin](/latest/openlit/instance-admin) changes apply to the whole instance. They're recorded against the acting admin's current organisation. `instance_auth.updated` lists only the changed variable names, never their values.
+
Each event stores the organisation, the project and database config when known, the actor, the action, the target type and ID, the metadata, and the time.
## Retention
diff --git a/docs/latest/openlit/configuration.mdx b/docs/latest/openlit/configuration.mdx
index 7418125a..2ab66f83 100644
--- a/docs/latest/openlit/configuration.mdx
+++ b/docs/latest/openlit/configuration.mdx
@@ -141,6 +141,64 @@ For detailed OAuth setup instructions, see the [OAuth Authentication Setup](/lat
```
</ResponseField>
+<ResponseField name="AZURE_AD_CLIENT_ID">
+ Application (client) ID of the Microsoft Entra ID app registration used for Microsoft sign-in.
+
+ **Example**:
+ ```yaml
+ export AZURE_AD_CLIENT_ID=your-azure-client-id
+ ```
+</ResponseField>
+
+<ResponseField name="AZURE_AD_CLIENT_SECRET">
+ Client secret of the Microsoft Entra ID app registration used for Microsoft sign-in.
+
+ **Example**:
+ ```yaml
+ export AZURE_AD_CLIENT_SECRET=your-azure-client-secret
+ ```
+</ResponseField>
+
+<ResponseField name="AZURE_AD_TENANT_ID">
+ Optional. The Microsoft Entra directory (tenant) ID or a verified domain, such as `contoso.onmicrosoft.com`. Defaults to `common`, which accepts work, school, and personal Microsoft accounts from any directory. Set a single directory to limit sign-in to your organisation: OpenLIT only links a Microsoft sign-in to an existing account by email when this names one directory. `organizations` and `consumers` are also accepted.
+
+ **Example**:
+ ```yaml
+ export AZURE_AD_TENANT_ID=00000000-0000-0000-0000-000000000000
+ ```
+</ResponseField>
+
+<ResponseField name="OKTA_CLIENT_ID">
+ Client ID of the Okta OIDC web application used for Okta sign-in.
+
+ **Example**:
+ ```yaml
+ export OKTA_CLIENT_ID=your-okta-client-id
+ ```
+</ResponseField>
+
+<ResponseField name="OKTA_CLIENT_SECRET">
+ Client secret of the Okta OIDC web application used for Okta sign-in.
+
+ **Example**:
+ ```yaml
+ export OKTA_CLIENT_SECRET=your-okta-client-secret
+ ```
+</ResponseField>
+
+<ResponseField name="OKTA_ISSUER">
+ Issuer URL of your Okta authorization server. It must be a public `https` URL, such as `https://your-domain.okta.com/oauth2/default`.
+
+ **Example**:
+ ```yaml
+ export OKTA_ISSUER=https://your-domain.okta.com/oauth2/default
+ ```
+</ResponseField>
+
+<Tip>
+In OpenLIT Enterprise, the instance admin can also set these values from **Instance admin → Auth** without redeploying. Values saved there override these variables. See [Instance admin](/latest/openlit/instance-admin#auth).
+</Tip>
+
## Server variables
<ResponseField name="PORT">
@@ -482,6 +540,12 @@ GOOGLE_CLIENT_ID="your-google-client-id"
GOOGLE_CLIENT_SECRET="your-google-client-secret"
GITHUB_CLIENT_ID="your-github-client-id"
GITHUB_CLIENT_SECRET="your-github-client-secret"
+AZURE_AD_CLIENT_ID="your-azure-client-id"
+AZURE_AD_CLIENT_SECRET="your-azure-client-secret"
+AZURE_AD_TENANT_ID="your-directory-id" # optional, defaults to common
+OKTA_CLIENT_ID="your-okta-client-id"
+OKTA_CLIENT_SECRET="your-okta-client-secret"
+OKTA_ISSUER="https://your-domain.okta.com/oauth2/default"
# Server Configuration (Optional)
# PORT is for Docker Compose; use DOCKER_PORT instead for Kubernetes or a raw container run
diff --git a/docs/latest/openlit/enterprise.mdx b/docs/latest/openlit/enterprise.mdx
index 3925f51e..0c8cfc61 100644
--- a/docs/latest/openlit/enterprise.mdx
+++ b/docs/latest/openlit/enterprise.mdx
@@ -18,15 +18,19 @@ Pages for enterprise features are marked with an **Enterprise** tag in the sideb
| Organisations, projects, environments, and built-in roles (Owner, Admin, Member) | ✓ | ✓ |
| [Threshold alerts](/latest/openlit/alerts#create-a-threshold-alert) on live error rate, latency, tokens, and cost, with in-app notifications | ✓ | ✓ |
| API keys with full access | ✓ | ✓ |
+| [Sign in with Google, GitHub, Microsoft, and Okta](/latest/openlit/oauth) using environment variables | ✓ | ✓ |
| [Role-based access control](/latest/openlit/rbac): custom role groups and direct user permissions | | ✓ |
| [Per-feature API key access](/latest/openlit/rbac#api-key-access): restrict each key to specific features | | ✓ |
| [Audit logs](/latest/openlit/audit-logs) for organisation, member, role, license, API key, connector, and configuration changes across OpenLIT features | | ✓ |
| [Event alerts](/latest/openlit/alerts#event-alerts) on access, API key, Vault, connector, scanner, and other changes, and notification destinations with message templates for every alert | | ✓ |
| Premium connectors: [Slack, email, webhook, Discord, PagerDuty, Opsgenie, and Datadog notifications](/latest/openlit/connectors/notification); [Datadog and New Relic data sources](/latest/openlit/connectors/datasource#enterprise-data-source-connectors) | | ✓ |
| [GPUs](/latest/openlit/gpus): fleet health, workloads, kernels, errors, cost, and Otter recommendations¹ | | ✓ |
+| [Instance admin](/latest/openlit/instance-admin): manage and test sign-in providers in the app, and add or remove instance admins² | | ✓ |
¹ The GPUs page comes with the enterprise build and doesn't need a separate license feature. The community edition collects GPU metrics with the [GPU collector](/latest/gpu-collector/quickstart).
+² Instance admin settings apply to the whole instance. They unlock when any organisation on the instance has an active enterprise license, and don't need a separate license feature.
+
## Enterprise features
<CardGroup cols={2}>
@@ -48,6 +52,9 @@ Pages for enterprise features are marked with an **Enterprise** tag in the sideb
<Card title="GPUs" href="/latest/openlit/gpus" icon="microchip">
GPU fleet health, workloads, kernels, errors, and cost
</Card>
+ <Card title="Instance admin" href="/latest/openlit/instance-admin" icon="user-shield">
+ Sign-in provider settings and instance admins for the whole deployment
+ </Card>
</CardGroup>
## Get OpenLIT Enterprise
@@ -65,7 +72,7 @@ OpenLIT Enterprise is built from a private repository and unlocked with a licens
## How licensing works
-Enterprise features are licensed per organisation. A license lists the enterprise features it unlocks and is signed, so it can't be modified.
+Enterprise features are licensed per organisation. A license lists the enterprise features it unlocks and is signed, so it can't be modified. [Instance admin](/latest/openlit/instance-admin) settings are the exception: they cover the whole instance and unlock when any organisation has an active license.
<Frame>
<img src="/images/enterprise/licensing.png" alt="Organisation Licensing tab with an active enterprise license and the features it unlocks" />
diff --git a/docs/latest/openlit/instance-admin.mdx b/docs/latest/openlit/instance-admin.mdx
new file mode 100644
index 00000000..d1375ddc
--- /dev/null
+++ b/docs/latest/openlit/instance-admin.mdx
@@ -0,0 +1,189 @@
+---
+title: 'Instance admin'
+description: 'Manage settings for the whole OpenLIT instance, including sign-in providers and the people who can change them'
+icon: 'user-shield'
+tag: 'Enterprise'
+---
+
+import EnterpriseFeature from '/snippets/enterprise-feature.mdx';
+
+<EnterpriseFeature />
+
+The instance admin area holds settings that apply to the whole OpenLIT deployment rather than to one organisation or project. It has its own layout, without the organisation, project, or database switchers, and only instance admins can open it.
+
+The instance admin area has two pages:
+
+- **[Auth](#auth)**: set up and test Google, GitHub, Microsoft, and Okta sign-in without redeploying.
+- **[Admins](#admins)**: choose who else can manage instance settings.
+
+## Who is the instance admin
+
+The first account created on the instance is the **primary instance admin**. On a standard install this is the seeded `[email protected]` account. On installs that don't run the seed, it's the first person to register.
+
+- The primary admin can't be removed, so the instance always has an admin.
+- The primary admin can [add more admins](#admins).
+- Instance admin is separate from organisation roles. Being an organisation **Owner** doesn't make someone an instance admin, and being an instance admin doesn't change their organisation access.
+
+## Open the instance admin area
+
+Instance admins see an **Instance admin** entry in two places:
+
+- **Settings** in the sidebar
+- The account menu at the bottom of the sidebar
+
+Both open `/admin`. Anyone else who opens `/admin` is sent back to the home page, and the instance admin APIs return `403`.
+
+<Frame>
+ <img src="/images/enterprise/instance-admin-settings-entry.png" alt="Settings panel in the sidebar with the Instance admin entry below OpenAPI Spec" />
+</Frame>
+
+Select **Back to app** in the admin sidebar to return to your organisation.
+
+## Availability
+
+| | Community | Enterprise |
+| --- | :---: | :---: |
+| Sign in with Google, GitHub, Microsoft, and Okta using [environment variables](/latest/openlit/oauth) | ✓ | ✓ |
+| First account is the instance admin | ✓ | ✓ |
+| [Auth](#auth): manage and test sign-in providers in the app | | ✓ |
+| [Admins](#admins): add and remove instance admins | | ✓ |
+
+The instance admin pages need the [OpenLIT Enterprise](/latest/openlit/enterprise) build and an active enterprise license on **at least one organisation** on the instance. They don't need a specific license feature. Without a license, the pages are locked and the APIs return `403` with `upgrade_required`.
+
+In the community edition, `/admin` opens for the instance admin but has no settings pages.
+
+## Auth
+
+**Auth** (`/admin/auth`) shows every sign-in provider OpenLIT supports. Saved values override the deployment's [environment variables](/latest/openlit/configuration#oauth-authentication-variables) and apply on the next sign-in, with no restart.
+
+<Frame>
+ <img src="/images/enterprise/instance-admin-auth.png" alt="Auth page with provider tiles for Google, GitHub, Microsoft, and Okta, the Okta form, and a credential test result" />
+</Frame>
+
+### Provider status
+
+Each provider tile shows whether its button appears on the sign-in page:
+
+| Status | Meaning |
+| --- | --- |
+| **Shown on sign-in** | Every required value is set |
+| **Incomplete** | Some values are set; the form lists the missing fields |
+| **Not configured** | No values are set |
+
+A dot next to a provider's name means it has unsaved changes. If more providers are available than fit on screen, use the arrows on either side of the row to scroll.
+
+### Configure a provider
+
+<Steps>
+ <Step title="Select the provider">
+ Select a provider tile to open its form. The form shows the redirect URI to register with the provider.
+ </Step>
+ <Step title="Enter the values">
+ Each field shows where its current value comes from: **Saved for this instance**, **Deployment environment**, or **Not configured**.
+ - Client IDs, the Microsoft tenant ID, and the Okta issuer are shown.
+ - Client secrets are never shown again after they're saved. Leave a secret field empty to keep the current secret.
+ </Step>
+ <Step title="Test the credentials">
+ Select **Test credentials**. See [Test credentials](#test-credentials).
+ </Step>
+ <Step title="Save">
+ Select **Save changes**. The provider's button appears on the sign-in page on the next sign-in.
+ </Step>
+</Steps>
+
+To go back to the deployment's value for a field, select **Use deployment value** below it and save.
+
+### Test credentials
+
+**Test credentials** checks the values in the form with the provider before you save them. Empty fields use the saved or deployment value. Nothing is saved, and secrets are never shown in the result.
+
+| Provider | What's checked |
+| --- | --- |
+| Google | Client ID and secret |
+| GitHub | Client ID and secret |
+| Microsoft | Tenant, then client ID and secret |
+| Okta | Issuer, then client ID and secret |
+
+The result shows whether the provider accepted the credentials, plus the provider's error code when it didn't (for example `invalid_client`).
+
+<Note>
+A successful test confirms the client ID and secret. It doesn't confirm that the redirect URI is registered with the provider, so check that separately.
+</Note>
+
+With the Microsoft tenant set to `common`, Microsoft may not confirm credentials that are correct, and the test reports that they couldn't be confirmed. Set a single directory for a definite answer.
+
+### Validation and storage
+
+- The Okta issuer must be a public `https` URL. IP addresses, `localhost`, and addresses that resolve to a private network are rejected.
+- The Microsoft tenant must be a directory ID, a domain, `common`, `organizations`, or `consumers`.
+- Saved values are encrypted at rest.
+- Saving is recorded in [Audit Logs](/latest/openlit/audit-logs) as `instance_auth.updated`, listing only the changed variable names, never their values.
+
+## Admins
+
+**Admins** (`/admin/admins`) lists everyone who can manage instance settings. For each admin it shows who added them and when.
+
+<Frame>
+ <img src="/images/enterprise/instance-admin-admins.png" alt="Admins page with an add-by-email form, the primary admin, and an added admin with a Remove button" />
+</Frame>
+
+### Add an admin
+
+1. Enter the person's email under **Add an admin by email**.
+2. Select **Add admin**.
+
+The person needs an OpenLIT account on this instance first. Ask them to sign up or sign in once before you add them. They get access to the instance admin area on their next page load.
+
+### Remove an admin
+
+Select **Remove** next to an admin and confirm. They lose access to instance settings on their next request. Their account and organisation access don't change.
+
+- The primary admin can't be removed.
+- You can't remove yourself. Ask another admin to remove you.
+
+Adding and removing admins is recorded in [Audit Logs](/latest/openlit/audit-logs) as `instance_admin.added` and `instance_admin.removed`.
+
+## Audit logs
+
+Instance admin actions are recorded against the acting admin's current organisation, when that organisation is licensed for [Audit Logs](/latest/openlit/audit-logs).
+
+| Action | Recorded when |
+| --- | --- |
+| `instance_auth.updated` | Sign-in provider settings are saved |
+| `instance_admin.added` | An instance admin is added |
+| `instance_admin.removed` | An instance admin is removed |
+
+## Troubleshooting
+
+<AccordionGroup>
+ <Accordion title="I don't see Instance admin in Settings">
+ - Only instance admins see the entry. Check with the primary admin that you were added on the **Admins** page.
+ - The community edition has no instance settings pages, so the entry is hidden there.
+ </Accordion>
+
+ <Accordion title="The Auth or Admins page is locked">
+ Apply an active enterprise license to any organisation on the instance. See [How licensing works](/latest/openlit/enterprise#how-licensing-works).
+ </Accordion>
+
+ <Accordion title="No account uses that email">
+ The person must have an OpenLIT account before they can be made an admin. Ask them to sign up on this instance, then add them again.
+ </Accordion>
+
+ <Accordion title="A provider is saved but its button doesn't appear">
+ Open the provider on **Auth** and check its status. **Incomplete** lists the missing fields. For example, Okta needs a client ID, client secret, and issuer.
+ </Accordion>
+</AccordionGroup>
+
+---
+
+<CardGroup cols={3}>
+ <Card title="Sign-in providers" href="/latest/openlit/oauth" icon="shield-check">
+ Set up Google, GitHub, Microsoft, and Okta sign-in
+ </Card>
+ <Card title="OpenLIT Enterprise" href="/latest/openlit/enterprise" icon="crown">
+ Enterprise features and how licensing works
+ </Card>
+ <Card title="Audit Logs" href="/latest/openlit/audit-logs" icon="clock-rotate-left">
+ Who changed what across your organisation
+ </Card>
+</CardGroup>
diff --git a/docs/latest/openlit/oauth.mdx b/docs/latest/openlit/oauth.mdx
index f0bc367b..d4eed132 100644
--- a/docs/latest/openlit/oauth.mdx
+++ b/docs/latest/openlit/oauth.mdx
@@ -1,27 +1,44 @@
---
title: 'OAuth'
-description: 'Configure Google and GitHub OAuth authentication for OpenLIT using NextAuth.js'
+description: 'Configure Google, GitHub, Microsoft, and Okta sign-in for OpenLIT'
icon: 'shield-check'
---
-This guide walks you through setting up OAuth authentication with Google and GitHub providers in OpenLIT using [NextAuth.js](https://next-auth.js.org/).
+This guide walks you through setting up sign-in with Google, GitHub, Microsoft, and Okta in OpenLIT using [NextAuth.js](https://next-auth.js.org/).
## Overview
-OpenLIT supports OAuth authentication through NextAuth.js with these providers:
-- **Google OAuth** - Sign in with Google accounts
-- **GitHub OAuth** - Sign in with GitHub accounts
+OpenLIT supports these sign-in methods:
+- **Google** - Sign in with Google accounts
+- **GitHub** - Sign in with GitHub accounts
+- **Microsoft** - Sign in with Microsoft Entra ID (work, school, or personal Microsoft accounts)
+- **Okta** - Sign in through your Okta organisation
- **Email/Password** - Traditional credentials-based authentication
+Each provider is configured with environment variables, in both the community edition and OpenLIT Enterprise. A provider's button appears on the sign-in page only when all of its required values are set.
+
+| Provider | Required variables | Optional variables | Redirect URI |
+| --- | --- | --- | --- |
+| Google | `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | | `/api/auth/callback/google` |
+| GitHub | `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET` | | `/api/auth/callback/github` |
+| Microsoft | `AZURE_AD_CLIENT_ID`, `AZURE_AD_CLIENT_SECRET` | `AZURE_AD_TENANT_ID` | `/api/auth/callback/azure-ad` |
+| Okta | `OKTA_CLIENT_ID`, `OKTA_CLIENT_SECRET`, `OKTA_ISSUER` | | `/api/auth/callback/okta` |
+
+Prefix each redirect URI with your OpenLIT URL, for example `https://openlit.example.com/api/auth/callback/okta`.
+
+<Tip>
+In [OpenLIT Enterprise](/latest/openlit/enterprise), the instance admin can also set and test these values from **Instance admin → Auth** without redeploying. See [Instance admin](/latest/openlit/instance-admin#auth).
+</Tip>
+
NextAuth.js automatically handles:
- OAuth 2.0 authorization flow
- Token management and refresh
- User session management
- Security best practices
-When users sign in via OAuth, OpenLIT automatically:
+When users sign in with a provider, OpenLIT automatically:
- Creates new user accounts if they don't exist
-- Links OAuth accounts to existing email-based accounts
+- Links the provider to an existing account with the same email, when the provider has verified that email (see [Account linking](#account-linking))
- Syncs profile information (name, profile picture)
- Runs user setup and database configuration
@@ -137,6 +154,55 @@ When users sign in via OAuth, OpenLIT automatically:
If creating a GitHub App instead of OAuth App, set "Email addresses" permission to read-only to access private email addresses as mentioned in the [NextAuth.js documentation](https://next-auth.js.org/providers/github).
</Note>
+## Microsoft setup
+
+<Steps>
+ <Step title="Register an application">
+ In the [Microsoft Entra admin center](https://entra.microsoft.com/), go to **Identity** > **Applications** > **App registrations** and select **New registration**.
+ - **Name**: OpenLIT
+ - **Supported account types**: choose **Accounts in this organizational directory only** to limit sign-in to your organisation, or a multi-tenant option to accept other directories
+ - **Redirect URI**: select **Web** and enter `https://yourdomain.com/api/auth/callback/azure-ad` (use `http://localhost:3000/api/auth/callback/azure-ad` for local development)
+ </Step>
+
+ <Step title="Copy the IDs">
+ On the app's **Overview** page, copy the **Application (client) ID** for `AZURE_AD_CLIENT_ID`, and the **Directory (tenant) ID** for `AZURE_AD_TENANT_ID`.
+ </Step>
+
+ <Step title="Create a client secret">
+ Go to **Certificates & secrets** > **Client secrets** > **New client secret**. Copy the secret **Value** (not the secret ID) for `AZURE_AD_CLIENT_SECRET`. It's shown only once.
+ </Step>
+
+ <Step title="Choose the tenant">
+ - Set `AZURE_AD_TENANT_ID` to your directory ID or a verified domain to accept only your organisation. This is recommended.
+ - Leave it unset (or set `common`) to accept any Microsoft account. `organizations` accepts any work or school account, and `consumers` accepts only personal Microsoft accounts.
+ </Step>
+</Steps>
+
+<Warning>
+With `common`, `organizations`, or `consumers`, anyone with a Microsoft account can create an OpenLIT account. OpenLIT doesn't trust the email from these sign-ins to link to an existing account, because the admin of any directory can set it. Set a single directory if your users already have OpenLIT accounts and should be able to sign in with Microsoft.
+</Warning>
+
+## Okta setup
+
+<Steps>
+ <Step title="Create an app integration">
+ In the Okta Admin Console, go to **Applications** > **Applications** > **Create App Integration**. Select **OIDC - OpenID Connect** and **Web Application**.
+ </Step>
+
+ <Step title="Configure the redirect URI">
+ - **Sign-in redirect URIs**: `https://yourdomain.com/api/auth/callback/okta` (use `http://localhost:3000/api/auth/callback/okta` for local development)
+ - **Assignments**: assign the users or groups who should be able to sign in to OpenLIT
+ </Step>
+
+ <Step title="Copy the credentials">
+ From the app's **General** tab, copy the **Client ID** for `OKTA_CLIENT_ID` and the **Client secret** for `OKTA_CLIENT_SECRET`. Keep **Client authentication** set to **Client secret**.
+ </Step>
+
+ <Step title="Find the issuer">
+ Go to **Security** > **API** > **Authorization Servers** and copy the **Issuer URI** of the server you use, for example `https://your-domain.okta.com/oauth2/default`. Set it as `OKTA_ISSUER`. The issuer must be a public `https` URL.
+ </Step>
+</Steps>
+
## Environment Configuration
```.env.production
@@ -151,15 +217,27 @@ GOOGLE_CLIENT_SECRET=your-google-client-secret
# GitHub OAuth
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret
+
+# Microsoft Entra ID
+AZURE_AD_CLIENT_ID=your-azure-client-id
+AZURE_AD_CLIENT_SECRET=your-azure-client-secret
+AZURE_AD_TENANT_ID=your-directory-id # optional, defaults to common
+
+# Okta
+OKTA_CLIENT_ID=your-okta-client-id
+OKTA_CLIENT_SECRET=your-okta-client-secret
+OKTA_ISSUER=https://your-domain.okta.com/oauth2/default
```
### Production Setup
<Steps>
<Step title="Update OAuth app URLs">
- Update both Google and GitHub OAuth apps with production URLs:
+ Update each provider's app with production URLs:
- **Google**: Add `https://yourdomain.com` to origins and `https://yourdomain.com/api/auth/callback/google` to redirect URIs
- **GitHub**: Update callback URL to `https://yourdomain.com/api/auth/callback/github`
+ - **Microsoft**: Add `https://yourdomain.com/api/auth/callback/azure-ad` as a Web redirect URI
+ - **Okta**: Add `https://yourdomain.com/api/auth/callback/okta` as a sign-in redirect URI
</Step>
<Step title="HTTPS requirement">
@@ -171,11 +249,24 @@ GITHUB_CLIENT_SECRET=your-github-client-secret
### User management
-- **New Users**: Automatically created when signing in via OAuth for the first time
-- **Existing Users**: OAuth accounts are linked to existing email-based accounts
-- **Profile Sync**: Name and profile picture are synced from OAuth providers
+- **New Users**: Automatically created when signing in with a provider for the first time
+- **Existing Users**: A provider is linked to an existing account with the same email when the provider has verified the email (see below)
+- **Profile Sync**: Name and profile picture are synced from the provider when the account doesn't have them yet
- **Database Setup**: New users get proper database configurations and permissions
+### Account linking
+
+When someone signs in with a provider and an OpenLIT account already uses that email, OpenLIT links the provider to that account only when the provider vouches for the email:
+
+| Provider | Linked to an existing account when |
+| --- | --- |
+| Google | Google reports the email as verified |
+| GitHub | Always (GitHub returns the account's own primary email) |
+| Microsoft | `AZURE_AD_TENANT_ID` names a single directory |
+| Okta | Okta reports the email as verified |
+
+Otherwise the sign-in is refused and the user sees a message to sign in with the method they used originally. A provider identity that is already linked to the account can always sign in. If a provider reports an email as unverified, the sign-in is refused even when no account uses that email.
+
### Session management
NextAuth.js handles all session management including:
@@ -189,7 +280,9 @@ NextAuth.js handles all session management including:
<AccordionGroup>
<Accordion title="OAuth button not appearing">
**Solutions**:
+ - Check that every required variable for the provider is set. For example, Okta needs `OKTA_CLIENT_ID`, `OKTA_CLIENT_SECRET`, and `OKTA_ISSUER`
- Check that environment variables are set correctly
+ - In OpenLIT Enterprise, open **Instance admin → Auth**: each provider shows **Shown on sign-in**, **Incomplete** (with the missing fields), or **Not configured**
- Ensure `.env` file is in the correct directory (`src/client/`) for development
- You can create a `.env` file to in the same directory as the `docker-compose.yml` file with the creds
</Accordion>
@@ -203,11 +296,26 @@ NextAuth.js handles all session management including:
<Accordion title="Invalid client error">
**Solutions**:
+ - In OpenLIT Enterprise, use **Test credentials** on **Instance admin → Auth** to check the values with the provider
+ - For Microsoft, use the client secret **Value**, not the secret ID, and check that the secret hasn't expired
- Verify client credentials are copied correctly
- Check for extra spaces or characters in environment variables
- Ensure you're using credentials from the correct OAuth app
</Accordion>
+ <Accordion title="Sign-in refused for an existing account">
+ **Solutions**:
+ - The provider didn't verify the email, so OpenLIT won't link it to the existing account. See [Account linking](#account-linking)
+ - For Microsoft, set `AZURE_AD_TENANT_ID` to your directory instead of `common`
+ - Sign in with the method the account used originally (for example, email and password)
+ </Accordion>
+
+ <Accordion title="Okta issuer rejected">
+ **Solutions**:
+ - Use the full issuer URI from **Security** > **API** > **Authorization Servers**, such as `https://your-domain.okta.com/oauth2/default`
+ - The issuer must use `https` and a public hostname. IP addresses, `localhost`, and private network addresses are rejected
+ </Accordion>
+
<Accordion title="NEXTAUTH_URL mismatch">
**Solutions**:
- Set `NEXTAUTH_URL=http://localhost:3000` for development
diff --git a/env.example b/env.example
index 20f6dc6a..0fb9ac8e 100644
--- a/env.example
+++ b/env.example
@@ -30,6 +30,20 @@ GOOGLE_CLIENT_SECRET=
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
+# Microsoft Entra ID (Azure AD)
+# Redirect URI: {NEXTAUTH_URL}/api/auth/callback/azure-ad
+AZURE_AD_CLIENT_ID=
+AZURE_AD_CLIENT_SECRET=
+# Directory tenant ID, or common / organizations / consumers.
+AZURE_AD_TENANT_ID=
+
+# Okta
+# Issuer example: https://your-domain.okta.com/oauth2/default
+# Redirect URI: {NEXTAUTH_URL}/api/auth/callback/okta
+OKTA_CLIENT_ID=
+OKTA_CLIENT_SECRET=
+OKTA_ISSUER=
+
# =============================================================================
# OTLP ingest (first-party receiver in the OpenLIT image)
# =============================================================================
diff --git a/src/client/.env.example b/src/client/.env.example
index 29396a71..617b53fe 100644
--- a/src/client/.env.example
+++ b/src/client/.env.example
@@ -4,6 +4,17 @@ GOOGLE_CLIENT_SECRET=
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
+# Microsoft Entra ID. Redirect URI: {NEXTAUTH_URL}/api/auth/callback/azure-ad
+AZURE_AD_CLIENT_ID=
+AZURE_AD_CLIENT_SECRET=
+AZURE_AD_TENANT_ID=
+
+# Okta. Issuer example: https://your-domain.okta.com/oauth2/default
+# Redirect URI: {NEXTAUTH_URL}/api/auth/callback/okta
+OKTA_CLIENT_ID=
+OKTA_CLIENT_SECRET=
+OKTA_ISSUER=
+
# Generate NEXTAUTH_SECRET by running command : `node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"` on your terminal
NEXTAUTH_SECRET=
diff --git a/src/client/prisma/migrations/20261103130000_users_created_at_index/migration.sql b/src/client/prisma/migrations/20261103130000_users_created_at_index/migration.sql
new file mode 100644
index 00000000..73aa3d30
--- /dev/null
+++ b/src/client/prisma/migrations/20261103130000_users_created_at_index/migration.sql
@@ -0,0 +1,2 @@
+-- CreateIndex
+CREATE INDEX "users_createdAt_id_idx" ON "users"("createdAt", "id");
diff --git a/src/client/prisma/schema.prisma b/src/client/prisma/schema.prisma
index f55faa4e..9e602ce9 100644
--- a/src/client/prisma/schema.prisma
+++ b/src/client/prisma/schema.prisma
@@ -61,6 +61,8 @@ model User {
organisations OrganisationUser[]
projectMemberships ProjectUser[]
+ // The instance admin is the earliest account; keep that lookup indexed.
+ @@index([createdAt, id])
@@map("users")
}
diff --git a/src/client/src/__tests__/app/api/organisation/overview/route.test.ts b/src/client/src/__tests__/app/api/organisation/overview/route.test.ts
new file mode 100644
index 00000000..de679442
--- /dev/null
+++ b/src/client/src/__tests__/app/api/organisation/overview/route.test.ts
@@ -0,0 +1,27 @@
+import { POST as overviewPost } from "@/app/api/organisation/[id]/overview/route";
+import { POST as filtersPost } from "@/app/api/organisation/[id]/overview/filters/route";
+import { POST as spendLimitsPost } from "@/app/api/organisation/[id]/spend-limits/route";
+
+describe("CE organisation overview routes", () => {
+ it("returns upgrade required and does not read a database", async () => {
+ const response = overviewPost();
+ expect(response.status).toBe(403);
+ await expect(response.json()).resolves.toMatchObject({
+ code: "upgrade_required",
+ featureId: "enterprise.organisation-overview",
+ });
+ });
+
+ it("locks the filters and spend-limit routes the same way", async () => {
+ const filters = filtersPost();
+ const limits = spendLimitsPost();
+ expect(filters.status).toBe(403);
+ expect(limits.status).toBe(403);
+ await expect(filters.json()).resolves.toMatchObject({
+ code: "upgrade_required",
+ });
+ await expect(limits.json()).resolves.toMatchObject({
+ code: "upgrade_required",
+ });
+ });
+});
diff --git a/src/client/src/__tests__/app/auth-signin.test.ts b/src/client/src/__tests__/app/auth-signin.test.ts
new file mode 100644
index 00000000..f3d795bc
--- /dev/null
+++ b/src/client/src/__tests__/app/auth-signin.test.ts
@@ -0,0 +1,142 @@
+/**
+ * @jest-environment node
+ */
+const mockAccountFindFirst = jest.fn();
+const mockAccountCreate = jest.fn();
+const mockBaseCreateUser = jest.fn();
+
+jest.mock("@prisma/client", () => ({
+ // auth.ts builds its client at import time, so read the mocks lazily.
+ PrismaClient: jest.fn(() => ({
+ account: {
+ findFirst: (...args: unknown[]) => mockAccountFindFirst(...args),
+ create: (...args: unknown[]) => mockAccountCreate(...args),
+ },
+ })),
+}));
+jest.mock("@next-auth/prisma-adapter", () => ({
+ PrismaAdapter: jest.fn(() => ({ createUser: (...args: unknown[]) => mockBaseCreateUser(...args) })),
+}));
+jest.mock("@/lib/db-config", () => ({ moveSharedDBConfigToDBUser: jest.fn() }));
+jest.mock("@/lib/organisation", () => ({ moveInvitationsToMembership: jest.fn() }));
+jest.mock("@/lib/user", () => ({
+ createNewUser: jest.fn(),
+ getUserByEmail: jest.fn(),
+ updateUser: jest.fn(),
+ doesPasswordMatches: jest.fn(),
+ getUserById: jest.fn(),
+}));
+jest.mock("@/lib/instance-admin", () => ({ isInstanceAdminUser: jest.fn() }));
+
+import { authOptions } from "@/app/auth";
+import { getUserByEmail } from "@/lib/user";
+import { moveSharedDBConfigToDBUser } from "@/lib/db-config";
+import { moveInvitationsToMembership } from "@/lib/organisation";
+
+const signIn = authOptions.callbacks!.signIn! as (args: any) => Promise<boolean | string>;
+const admin = { id: "admin-id", email: "[email protected]", name: "User", image: "x" };
+
+function attempt(provider: string, profile: Record<string, unknown>, user: Record<string, unknown> = {}) {
+ return signIn({
+ user: Object.assign(user, { id: "provider-sub", email: "[email protected]", ...user }),
+ account: { provider, providerAccountId: "provider-sub", type: "oauth" },
+ profile,
+ });
+}
+
+describe("OAuth sign-in account linking", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ (getUserByEmail as jest.Mock).mockResolvedValue(admin);
+ mockAccountFindFirst.mockResolvedValue(null);
+ });
+
+ it("refuses to link an unverified Microsoft email to an existing account", async () => {
+ await expect(
+ attempt("azure-ad", { email: "[email protected]" }, { emailTrusted: false })
+ ).resolves.toBe("/login?error=OAuthAccountNotLinked");
+ expect(mockAccountCreate).not.toHaveBeenCalled();
+ });
+
+ it("refuses Google and Okta emails the provider has not verified", async () => {
+ await expect(attempt("google", { email_verified: false })).resolves.toBe("/login?error=AccessDenied");
+ await expect(attempt("okta", {})).resolves.toBe("/login?error=OAuthAccountNotLinked");
+ expect(mockAccountCreate).not.toHaveBeenCalled();
+ });
+
+ it("links a verified email to the existing account", async () => {
+ await expect(attempt("google", { email_verified: true })).resolves.toBe(true);
+ expect(mockAccountCreate).toHaveBeenCalledWith(
+ expect.objectContaining({ data: expect.objectContaining({ userId: "admin-id", provider: "google" }) })
+ );
+ });
+
+ it("lets an identity already linked to the account sign in", async () => {
+ mockAccountFindFirst.mockImplementation(async ({ where }: any) =>
+ where.providerAccountId ? { userId: "admin-id" } : { id: "existing-link" }
+ );
+ await expect(
+ attempt("azure-ad", { email: "[email protected]" }, { emailTrusted: false })
+ ).resolves.toBe(true);
+ });
+
+ it("still allows new accounts when no account uses the email", async () => {
+ (getUserByEmail as jest.Mock).mockRejectedValue(new Error("Invalid email or password"));
+ await expect(attempt("okta", {})).resolves.toBe(true);
+ expect(mockAccountCreate).not.toHaveBeenCalled();
+ });
+
+ it("refuses an identity that is linked to a different account", async () => {
+ mockAccountFindFirst.mockResolvedValue({ userId: "someone-else" });
+ await expect(attempt("google", { email_verified: true })).resolves.toBe("/login?error=OAuthAccountNotLinked");
+ expect(mockAccountCreate).not.toHaveBeenCalled();
+ });
+
+ it("marks whether the provider vouched for a new account's email", async () => {
+ (getUserByEmail as jest.Mock).mockRejectedValue(new Error("Invalid email or password"));
+ const microsoft: Record<string, unknown> = { emailTrusted: false };
+ await attempt("azure-ad", { email: "[email protected]" }, microsoft);
+ expect(microsoft.emailVouched).toBe(false);
+
+ const google: Record<string, unknown> = {};
+ await attempt("google", { email_verified: true }, google);
+ expect(google.emailVouched).toBe(true);
+ });
+});
+
+describe("OAuth account creation", () => {
+ const createUser = authOptions.adapter!.createUser! as (user: any) => Promise<any>;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockBaseCreateUser.mockImplementation(async (data: any) => ({ id: "new-user", ...data }));
+ });
+
+ it("stores only user columns from the provider profile", async () => {
+ await createUser({
+ name: "Ada",
+ email: " [email protected] ",
+ image: null,
+ emailVerified: null,
+ emailTrusted: false,
+ emailVouched: false,
+ tid: "tenant",
+ });
+ expect(mockBaseCreateUser).toHaveBeenCalledWith({
+ name: "Ada",
+ email: "[email protected]",
+ image: null,
+ emailVerified: null,
+ });
+ });
+
+ it("only claims invitations and shared configs for a vouched email", async () => {
+ await createUser({ name: "Attacker", email: "[email protected]", emailVouched: false });
+ expect(moveInvitationsToMembership).not.toHaveBeenCalled();
+ expect(moveSharedDBConfigToDBUser).not.toHaveBeenCalled();
+
+ await createUser({ name: "Invitee", email: "[email protected]", emailVouched: true });
+ expect(moveInvitationsToMembership).toHaveBeenCalledWith("[email protected]", "new-user");
+ expect(moveSharedDBConfigToDBUser).toHaveBeenCalledWith("[email protected]", "new-user");
+ });
+});
diff --git a/src/client/src/__tests__/features/features.test.ts b/src/client/src/__tests__/features/features.test.ts
index d95ce154..2c94a5ff 100644
--- a/src/client/src/__tests__/features/features.test.ts
+++ b/src/client/src/__tests__/features/features.test.ts
@@ -12,6 +12,7 @@ import { onOrganisationChanged } from "@/features/organisation";
import { canManageOrganisation } from "@/features/organisation-access";
import { FEATURES as REGISTRY_FEATURES } from "@/features/registry";
import { getEnterpriseSidebarItems } from "@/features/sidebar";
+import { getAdminSidebarItems } from "@/features/admin-sidebar";
beforeAll(() => {
Object.defineProperty(global, "Response", {
@@ -73,6 +74,8 @@ describe("CE feature fallbacks", () => {
it("keeps enterprise sidebar and organisation hooks as CE no-ops", async () => {
expect(getEnterpriseSidebarItems("monitoring", "icon")).toEqual([]);
expect(getEnterpriseSidebarItems("configuration", "icon")).toEqual([]);
+ expect(getEnterpriseSidebarItems("settings", "icon")).toEqual([]);
+ expect(getAdminSidebarItems("icon")).toEqual([]);
await expect(onOrganisationChanged("org-1")).resolves.toBeUndefined();
await expect(
canManageOrganisation({
diff --git a/src/client/src/__tests__/lib/auth/oauth-providers.test.ts b/src/client/src/__tests__/lib/auth/oauth-providers.test.ts
new file mode 100644
index 00000000..e1233b57
--- /dev/null
+++ b/src/client/src/__tests__/lib/auth/oauth-providers.test.ts
@@ -0,0 +1,145 @@
+jest.mock("@/lib/instance-env/public-host", () => ({ resolvesToPublicHost: jest.fn() }));
+
+import { resolvesToPublicHost } from "@/lib/instance-env/public-host";
+import {
+ buildOAuthProviders,
+ emailFromProfile,
+ isEmailExplicitlyUnverified,
+ isEmailVouched,
+ oauthProfilePatch,
+} from "@/lib/auth/oauth-providers";
+
+function providerById(providers: Awaited<ReturnType<typeof buildOAuthProviders>>, id: string) {
+ return providers.find((provider) => provider.id === id);
+}
+
+describe("oauth providers", () => {
+ const keys = [
+ "GOOGLE_CLIENT_ID",
+ "GOOGLE_CLIENT_SECRET",
+ "GITHUB_CLIENT_ID",
+ "GITHUB_CLIENT_SECRET",
+ "AZURE_AD_CLIENT_ID",
+ "AZURE_AD_CLIENT_SECRET",
+ "AZURE_AD_TENANT_ID",
+ "OKTA_CLIENT_ID",
+ "OKTA_CLIENT_SECRET",
+ "OKTA_ISSUER",
+ ];
+ const previous = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
+
+ beforeEach(() => {
+ for (const key of keys) delete process.env[key];
+ (resolvesToPublicHost as jest.Mock).mockReset().mockResolvedValue(true);
+ });
+
+ it("leaves Okta off when the issuer resolves to a private address", async () => {
+ process.env.OKTA_CLIENT_ID = "okta-client";
+ process.env.OKTA_CLIENT_SECRET = "okta-secret";
+ process.env.OKTA_ISSUER = "https://acme.okta.com/oauth2/default";
+ (resolvesToPublicHost as jest.Mock).mockResolvedValue(false);
+ await expect(buildOAuthProviders({})).resolves.toEqual([]);
+ expect(resolvesToPublicHost).toHaveBeenCalledWith("acme.okta.com");
+ });
+
+ afterAll(() => {
+ for (const [key, value] of Object.entries(previous)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ });
+
+ it("stays empty until a provider has the required values", async () => {
+ await expect(buildOAuthProviders({})).resolves.toEqual([]);
+ process.env.AZURE_AD_CLIENT_ID = "azure-client";
+ await expect(buildOAuthProviders({})).resolves.toEqual([]);
+ process.env.OKTA_CLIENT_ID = "okta-client";
+ process.env.OKTA_CLIENT_SECRET = "okta-secret";
+ await expect(buildOAuthProviders({})).resolves.toEqual([]);
+ });
+
+ it("enables microsoft and okta from environment variables", async () => {
+ process.env.AZURE_AD_CLIENT_ID = "azure-client";
+ process.env.AZURE_AD_CLIENT_SECRET = "azure-secret";
+ process.env.OKTA_CLIENT_ID = "okta-client";
+ process.env.OKTA_CLIENT_SECRET = "okta-secret";
+ process.env.OKTA_ISSUER = "https://acme.okta.com/oauth2/default/";
+
+ const providers = await buildOAuthProviders({});
+ expect(providers.map((provider) => provider.id)).toEqual(["azure-ad", "okta"]);
+ expect(providerById(providers, "azure-ad")?.options).toMatchObject({
+ clientId: "azure-client",
+ tenantId: "common",
+ });
+ expect(providerById(providers, "okta")).toMatchObject({
+ wellKnown: "https://acme.okta.com/oauth2/default/.well-known/openid-configuration",
+ });
+ });
+
+ it("prefers a saved instance value over the deployment environment", async () => {
+ process.env.GOOGLE_CLIENT_ID = "env-client";
+ process.env.GOOGLE_CLIENT_SECRET = "env-secret";
+
+ const providers = await buildOAuthProviders({
+ GOOGLE_CLIENT_ID: "saved-client",
+ GOOGLE_CLIENT_SECRET: "saved-secret",
+ });
+ expect(providerById(providers, "google")?.options).toMatchObject({
+ clientId: "saved-client",
+ clientSecret: "saved-secret",
+ });
+ });
+
+ it("does not enable a provider when the saved value is invalid", async () => {
+ process.env.OKTA_CLIENT_ID = "okta-client";
+ process.env.OKTA_CLIENT_SECRET = "okta-secret";
+ process.env.OKTA_ISSUER = "https://acme.okta.com";
+
+ await expect(buildOAuthProviders({ OKTA_ISSUER: "http://localhost" })).resolves.toEqual([]);
+ });
+
+ it("reads microsoft and github profile fields", () => {
+ expect(emailFromProfile({ preferred_username: "[email protected]" })).toBe("[email protected]");
+ expect(emailFromProfile({ email: "not-an-email" })).toBeNull();
+ expect(oauthProfilePatch("github", { login: "ada", avatar_url: "https://example.com/a.png" })).toEqual({
+ name: "ada",
+ image: "https://example.com/a.png",
+ });
+ expect(oauthProfilePatch("azure-ad", { name: "Ada Lovelace", picture: "https://example.com/ada.png" })).toEqual({
+ name: "Ada Lovelace",
+ image: "https://example.com/ada.png",
+ });
+ });
+
+ it("only vouches for emails the provider has verified", () => {
+ expect(isEmailVouched("google", { email_verified: true })).toBe(true);
+ expect(isEmailVouched("google", { email_verified: false })).toBe(false);
+ expect(isEmailVouched("google", {})).toBe(false);
+ expect(isEmailVouched("okta", { email_verified: "true" })).toBe(true);
+ expect(isEmailVouched("okta", {})).toBe(false);
+ expect(isEmailVouched("github", {})).toBe(true);
+ expect(isEmailVouched("azure-ad", { email: "[email protected]" }, { emailTrusted: false })).toBe(false);
+ expect(isEmailVouched("azure-ad", { email: "[email protected]" }, { emailTrusted: true })).toBe(true);
+ expect(isEmailVouched("unknown", { email_verified: true })).toBe(false);
+ expect(isEmailExplicitlyUnverified({ email_verified: false })).toBe(true);
+ expect(isEmailExplicitlyUnverified({})).toBe(false);
+ });
+
+ it("never trusts Microsoft emails when any tenant may sign in", async () => {
+ process.env.AZURE_AD_CLIENT_ID = "azure-client";
+ process.env.AZURE_AD_CLIENT_SECRET = "azure-secret";
+ const claims = { sub: "s", email: "[email protected]", name: "Attacker" };
+
+ for (const tenant of [undefined, "common", "organizations", "consumers"]) {
+ if (tenant) process.env.AZURE_AD_TENANT_ID = tenant;
+ else delete process.env.AZURE_AD_TENANT_ID;
+ const azure = providerById(await buildOAuthProviders({}), "azure-ad") as any;
+ const user = await azure.options.profile(claims, {});
+ expect(user.emailTrusted).toBe(false);
+ }
+
+ process.env.AZURE_AD_TENANT_ID = "contoso.onmicrosoft.com";
+ const single = providerById(await buildOAuthProviders({}), "azure-ad") as any;
+ expect(await single.options.profile(claims, {})).toMatchObject({ emailTrusted: true });
+ });
+});
diff --git a/src/client/src/__tests__/lib/instance-admin/index.test.ts b/src/client/src/__tests__/lib/instance-admin/index.test.ts
new file mode 100644
index 00000000..11ec1acc
--- /dev/null
+++ b/src/client/src/__tests__/lib/instance-admin/index.test.ts
@@ -0,0 +1,38 @@
+jest.mock("@/lib/prisma", () => ({
+ __esModule: true,
+ default: { user: { findFirst: jest.fn() } },
+}));
+
+import prisma from "@/lib/prisma";
+import { getInstanceAdminUserId, isInstanceAdminUser } from "@/lib/instance-admin";
+
+const findFirst = prisma.user.findFirst as jest.Mock;
+
+describe("instance admin", () => {
+ beforeEach(() => findFirst.mockReset());
+
+ it("picks the earliest account, with id as the tie-break", async () => {
+ findFirst.mockResolvedValue({ id: "first-user" });
+ await expect(getInstanceAdminUserId()).resolves.toBe("first-user");
+ expect(findFirst).toHaveBeenCalledWith({
+ orderBy: [{ createdAt: "asc" }, { id: "asc" }],
+ select: { id: true },
+ });
+ });
+
+ it("is only true for the first account", async () => {
+ findFirst.mockResolvedValue({ id: "first-user" });
+ await expect(isInstanceAdminUser("first-user")).resolves.toBe(true);
+ await expect(isInstanceAdminUser("second-user")).resolves.toBe(false);
+ });
+
+ it("is false without a user id or when no account exists", async () => {
+ await expect(isInstanceAdminUser(undefined)).resolves.toBe(false);
+ await expect(isInstanceAdminUser(null)).resolves.toBe(false);
+ expect(findFirst).not.toHaveBeenCalled();
+
+ findFirst.mockResolvedValue(null);
+ await expect(getInstanceAdminUserId()).resolves.toBeNull();
+ await expect(isInstanceAdminUser("someone")).resolves.toBe(false);
+ });
+});
diff --git a/src/client/src/__tests__/lib/instance-admin/route.test.ts b/src/client/src/__tests__/lib/instance-admin/route.test.ts
new file mode 100644
index 00000000..4b56c8c1
--- /dev/null
+++ b/src/client/src/__tests__/lib/instance-admin/route.test.ts
@@ -0,0 +1,55 @@
+jest.mock("@/lib/session", () => ({ getCurrentUser: jest.fn() }));
+jest.mock("@/lib/instance-admin", () => ({ isInstanceAdminUser: jest.fn() }));
+
+import { getCurrentUser } from "@/lib/session";
+import { isInstanceAdminUser } from "@/lib/instance-admin";
+import { withInstanceAdmin } from "@/lib/instance-admin/route";
+
+class TestResponse {
+ constructor(private body: unknown, public status = 200) {}
+ static json(body: unknown, init?: { status?: number }) {
+ return new TestResponse(body, init?.status);
+ }
+ async json() {
+ return this.body;
+ }
+}
+
+describe("withInstanceAdmin", () => {
+ const originalResponse = global.Response;
+ const handler = jest.fn(async (_request: Request, _context: unknown) => TestResponse.json({ ok: true }) as unknown as Response);
+ const wrapped = withInstanceAdmin(handler);
+ const request = {} as Request;
+
+ beforeAll(() => {
+ (global as any).Response = TestResponse;
+ });
+ afterAll(() => {
+ (global as any).Response = originalResponse;
+ });
+ beforeEach(() => jest.clearAllMocks());
+
+ it("returns 401 without a signed-in user", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(null);
+ const response = await wrapped(request, {});
+ expect(response.status).toBe(401);
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it("returns 403 for a user who is not the instance admin", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: "member" });
+ (isInstanceAdminUser as jest.Mock).mockResolvedValue(false);
+ const response = await wrapped(request, {});
+ expect(response.status).toBe(403);
+ expect(isInstanceAdminUser).toHaveBeenCalledWith("member");
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it("calls the handler for the instance admin", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: "admin" });
+ (isInstanceAdminUser as jest.Mock).mockResolvedValue(true);
+ const response = await wrapped(request, { params: {} });
+ expect(response.status).toBe(200);
+ expect(handler).toHaveBeenCalledWith(request, { params: {} });
+ });
+});
diff --git a/src/client/src/__tests__/lib/instance-env/describe.test.ts b/src/client/src/__tests__/lib/instance-env/describe.test.ts
new file mode 100644
index 00000000..9c986774
--- /dev/null
+++ b/src/client/src/__tests__/lib/instance-env/describe.test.ts
@@ -0,0 +1,54 @@
+import { describeInstanceEnvironment } from "@/lib/instance-env/describe";
+
+describe("instance environment description", () => {
+ const previous = {
+ GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
+ GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET,
+ OKTA_ISSUER: process.env.OKTA_ISSUER,
+ };
+
+ afterEach(() => {
+ for (const [key, value] of Object.entries(previous)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ });
+
+ it("hides secrets and reports where each value comes from", async () => {
+ process.env.GOOGLE_CLIENT_ID = "env-client";
+ process.env.GOOGLE_CLIENT_SECRET = "env-secret";
+ delete process.env.OKTA_ISSUER;
+
+ const variables = await describeInstanceEnvironment({
+ GOOGLE_CLIENT_ID: "saved-client",
+ OKTA_CLIENT_SECRET: "saved-secret",
+ });
+ const byKey = Object.fromEntries(variables.map((variable) => [variable.key, variable]));
+
+ expect(byKey.GOOGLE_CLIENT_ID).toMatchObject({
+ source: "instance",
+ secret: false,
+ configured: true,
+ value: "saved-client",
+ });
+ expect(byKey.GOOGLE_CLIENT_SECRET).toMatchObject({
+ source: "environment",
+ secret: true,
+ configured: true,
+ value: null,
+ });
+ expect(byKey.OKTA_CLIENT_SECRET).toMatchObject({
+ source: "instance",
+ secret: true,
+ configured: true,
+ value: null,
+ });
+ expect(byKey.OKTA_ISSUER).toMatchObject({
+ source: "unset",
+ configured: false,
+ value: null,
+ });
+ expect(JSON.stringify(variables)).not.toContain("env-secret");
+ expect(JSON.stringify(variables)).not.toContain("saved-secret");
+ });
+});
diff --git a/src/client/src/__tests__/lib/instance-env/http.test.ts b/src/client/src/__tests__/lib/instance-env/http.test.ts
new file mode 100644
index 00000000..242dd99d
--- /dev/null
+++ b/src/client/src/__tests__/lib/instance-env/http.test.ts
@@ -0,0 +1,38 @@
+/**
+ * @jest-environment node
+ */
+jest.mock("@/lib/session", () => ({ getCurrentUser: jest.fn() }));
+jest.mock("@/lib/instance-admin", () => ({ isInstanceAdminUser: jest.fn() }));
+
+import { getCurrentUser } from "@/lib/session";
+import { isInstanceAdminUser } from "@/lib/instance-admin";
+import { GET, PATCH, VERIFY } from "@/lib/instance-env/http";
+
+const request = {} as Request;
+
+describe("instance auth route fallback", () => {
+ beforeEach(() => jest.clearAllMocks());
+
+ it("requires an enterprise plan for the instance admin", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: "admin" });
+ (isInstanceAdminUser as jest.Mock).mockResolvedValue(true);
+ for (const handler of [GET, PATCH, VERIFY]) {
+ const response = await handler(request, {});
+ expect(response.status).toBe(403);
+ await expect(response.json()).resolves.toMatchObject({
+ featureId: "enterprise.instance-admin",
+ });
+ }
+ });
+
+ it("checks the instance admin before reporting the plan", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(null);
+ expect((await GET(request, {})).status).toBe(401);
+
+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: "member" });
+ (isInstanceAdminUser as jest.Mock).mockResolvedValue(false);
+ const denied = await PATCH(request, {});
+ expect(denied.status).toBe(403);
+ await expect(denied.json()).resolves.not.toHaveProperty("featureId");
+ });
+});
diff --git a/src/client/src/__tests__/lib/instance-env/public-host.test.ts b/src/client/src/__tests__/lib/instance-env/public-host.test.ts
new file mode 100644
index 00000000..b9b4b6f4
--- /dev/null
+++ b/src/client/src/__tests__/lib/instance-env/public-host.test.ts
@@ -0,0 +1,43 @@
+jest.mock("dns/promises", () => ({ lookup: jest.fn() }));
+
+import { lookup } from "dns/promises";
+import { clearPublicHostCache, resolvesToPublicHost } from "@/lib/instance-env/public-host";
+
+const resolve = (...addresses: string[]) =>
+ (lookup as jest.Mock).mockResolvedValue(addresses.map((address) => ({ address, family: address.includes(":") ? 6 : 4 })));
+
+describe("resolvesToPublicHost", () => {
+ beforeEach(() => {
+ (lookup as jest.Mock).mockReset();
+ clearPublicHostCache();
+ });
+
+ it("accepts hosts whose addresses are all public", async () => {
+ resolve("34.1.2.3", "2600:1f18::1");
+ await expect(resolvesToPublicHost("acme.okta.com")).resolves.toBe(true);
+ });
+
+ it("rejects hosts with any private, loopback, link-local, or mapped address", async () => {
+ for (const address of ["10.0.0.5", "127.0.0.1", "169.254.169.254", "::1", "fd00::1", "::ffff:192.168.1.1"]) {
+ clearPublicHostCache();
+ resolve("34.1.2.3", address);
+ await expect(resolvesToPublicHost("rebind.example.com")).resolves.toBe(false);
+ }
+ });
+
+ it("rejects hosts that do not resolve", async () => {
+ (lookup as jest.Mock).mockRejectedValue(new Error("ENOTFOUND"));
+ await expect(resolvesToPublicHost("missing.example.com")).resolves.toBe(false);
+ (lookup as jest.Mock).mockResolvedValue([]);
+ clearPublicHostCache();
+ await expect(resolvesToPublicHost("empty.example.com")).resolves.toBe(false);
+ });
+
+ it("strips IPv6 brackets and caches results", async () => {
+ resolve("::1");
+ await expect(resolvesToPublicHost("[::1]")).resolves.toBe(false);
+ expect(lookup).toHaveBeenCalledWith("::1", { all: true });
+ await resolvesToPublicHost("[::1]");
+ expect(lookup).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/client/src/__tests__/lib/instance-env/store.test.ts b/src/client/src/__tests__/lib/instance-env/store.test.ts
new file mode 100644
index 00000000..f98f520f
--- /dev/null
+++ b/src/client/src/__tests__/lib/instance-env/store.test.ts
@@ -0,0 +1,7 @@
+import { loadInstanceEnvOverrides } from "@/lib/instance-env/store";
+
+describe("open source instance environment store", () => {
+ it("does not apply saved overrides", async () => {
+ await expect(loadInstanceEnvOverrides()).resolves.toEqual({});
+ });
+});
diff --git a/src/client/src/__tests__/lib/instance-env/validate.test.ts b/src/client/src/__tests__/lib/instance-env/validate.test.ts
new file mode 100644
index 00000000..951ab59e
--- /dev/null
+++ b/src/client/src/__tests__/lib/instance-env/validate.test.ts
@@ -0,0 +1,86 @@
+import { parseInstanceEnvUpdates } from "@/lib/instance-env/validate";
+import { normalizeOktaIssuer } from "@/lib/instance-env/values";
+
+describe("instance environment updates", () => {
+ it("rejects malformed payloads and unknown keys", () => {
+ expect(parseInstanceEnvUpdates(null)).toEqual({ ok: false, error: "malformed" });
+ expect(parseInstanceEnvUpdates([])).toEqual({ ok: false, error: "malformed" });
+ expect(parseInstanceEnvUpdates({})).toEqual({ ok: false, error: "malformed" });
+ expect(parseInstanceEnvUpdates({ updates: { key: "OKTA_ISSUER" } })).toEqual({
+ ok: false,
+ error: "malformed",
+ });
+ expect(parseInstanceEnvUpdates({ updates: [{ key: "DATABASE_URL", value: "x" }] })).toEqual({
+ ok: false,
+ error: "unknown_key",
+ });
+ expect(parseInstanceEnvUpdates({ updates: [{ value: "x" }] })).toEqual({
+ ok: false,
+ error: "malformed",
+ });
+ });
+
+ it("normalizes public issuers and rejects internal ones", () => {
+ expect(normalizeOktaIssuer("https://acme.okta.com/oauth2/default/")).toBe(
+ "https://acme.okta.com/oauth2/default"
+ );
+ expect(
+ normalizeOktaIssuer("https://acme.okta.com/oauth2/default/.well-known/openid-configuration")
+ ).toBe("https://acme.okta.com/oauth2/default");
+ expect(normalizeOktaIssuer("http://acme.okta.com")).toBeNull();
+ expect(normalizeOktaIssuer("https://localhost/oauth2/default")).toBeNull();
+ expect(normalizeOktaIssuer("https://169.254.169.254/latest")).toBeNull();
+ expect(normalizeOktaIssuer("https://user:[email protected]")).toBeNull();
+ expect(normalizeOktaIssuer("https://[::1]/oauth2/default")).toBeNull();
+ expect(normalizeOktaIssuer("https://[fd00::1]")).toBeNull();
+ expect(normalizeOktaIssuer("https://[::ffff:127.0.0.1]")).toBeNull();
+ });
+
+ it("accepts microsoft and okta values and clears blanks without keeping secrets", () => {
+ const parsed = parseInstanceEnvUpdates({
+ updates: [
+ { key: "AZURE_AD_CLIENT_ID", value: "11111111-1111-1111-1111-111111111111" },
+ { key: "AZURE_AD_CLIENT_SECRET", value: " " },
+ { key: "AZURE_AD_TENANT_ID", value: "COMMON" },
+ { key: "OKTA_CLIENT_ID", value: "okta-client" },
+ { key: "OKTA_CLIENT_SECRET", value: "okta-secret" },
+ { key: "OKTA_ISSUER", value: "https://acme.okta.com/oauth2/default/" },
+ { key: "GOOGLE_CLIENT_SECRET", clear: true },
+ { key: "GITHUB_CLIENT_ID", value: "" },
+ ],
+ });
+
+ expect(parsed).toEqual({
+ ok: true,
+ changes: [
+ { key: "AZURE_AD_CLIENT_ID", action: "set", value: "11111111-1111-1111-1111-111111111111" },
+ { key: "AZURE_AD_TENANT_ID", action: "set", value: "common" },
+ { key: "OKTA_CLIENT_ID", action: "set", value: "okta-client" },
+ { key: "OKTA_CLIENT_SECRET", action: "set", value: "okta-secret" },
+ { key: "OKTA_ISSUER", action: "set", value: "https://acme.okta.com/oauth2/default" },
+ { key: "GOOGLE_CLIENT_SECRET", action: "clear" },
+ { key: "GITHUB_CLIENT_ID", action: "clear" },
+ ],
+ });
+ expect(JSON.stringify(parseInstanceEnvUpdates({ updates: [{ key: "NOT_A_KEY", value: "secret-value" }] }))).not.toContain(
+ "secret-value"
+ );
+ });
+
+ it("rejects unsafe tenant, issuer, and secret values", () => {
+ expect(parseInstanceEnvUpdates({ updates: [{ key: "AZURE_AD_TENANT_ID", value: "../etc" }] })).toEqual({
+ ok: false,
+ error: "invalid_tenant",
+ });
+ expect(
+ parseInstanceEnvUpdates({
+ updates: [{ key: "OKTA_ISSUER", value: "https://metadata.google.internal" }],
+ })
+ ).toEqual({ ok: false, error: "invalid_issuer" });
+ expect(
+ parseInstanceEnvUpdates({
+ updates: [{ key: "OKTA_CLIENT_SECRET", value: "line\nbreak" }],
+ })
+ ).toEqual({ ok: false, error: "invalid_value" });
+ });
+});
diff --git a/src/client/src/__tests__/middleware/check-auth.test.ts b/src/client/src/__tests__/middleware/check-auth.test.ts
index 65382e2f..8a49db6f 100644
--- a/src/client/src/__tests__/middleware/check-auth.test.ts
+++ b/src/client/src/__tests__/middleware/check-auth.test.ts
@@ -524,6 +524,76 @@ describe('checkAuth', () => {
});
});
+ describe('instance admin area', () => {
+ it('redirects a signed-in user who is not the instance admin away from /admin pages', async () => {
+ (getToken as jest.Mock).mockResolvedValue({ hasCompletedOnboarding: true, isInstanceAdmin: false });
+ for (const path of ['/admin', '/admin/auth']) {
+ (NextResponse.redirect as jest.Mock).mockClear();
+ await middleware(makeRequest('GET', path) as any, makeFetchEvent());
+ const redirectCall = (NextResponse.redirect as jest.Mock).mock.calls[0][0];
+ expect(redirectCall.toString()).toBe('http://localhost/home');
+ }
+ });
+
+ it('treats a token without the admin claim as not admin', async () => {
+ (getToken as jest.Mock).mockResolvedValue({ hasCompletedOnboarding: true });
+ await middleware(makeRequest('GET', '/admin/auth') as any, makeFetchEvent());
+ expect(NextResponse.redirect).toHaveBeenCalled();
+ expect(NextResponse.next).not.toHaveBeenCalled();
+ });
+
+ it('lets the instance admin open /admin pages', async () => {
+ (getToken as jest.Mock).mockResolvedValue({ hasCompletedOnboarding: true, isInstanceAdmin: true });
+ await middleware(makeRequest('GET', '/admin/auth') as any, makeFetchEvent());
+ expect(NextResponse.next).toHaveBeenCalled();
+ expect(NextResponse.redirect).not.toHaveBeenCalled();
+ });
+
+ it('does not treat lookalike paths as the admin area', async () => {
+ (getToken as jest.Mock).mockResolvedValue({ hasCompletedOnboarding: true, isInstanceAdmin: false });
+ await middleware(makeRequest('GET', '/administrators') as any, makeFetchEvent());
+ expect(NextResponse.redirect).not.toHaveBeenCalled();
+ });
+
+ it('sends signed-out visitors to login with the admin page as callback', async () => {
+ (getToken as jest.Mock).mockResolvedValue(null);
+ await middleware(makeRequest('GET', '/admin/auth') as any, makeFetchEvent());
+ const redirectCall = (NextResponse.redirect as jest.Mock).mock.calls[0][0];
+ expect(redirectCall.toString()).toContain(`/login?callbackUrl=${encodeURIComponent('/admin/auth')}`);
+ });
+
+ it('returns 401 for signed-out admin API calls', async () => {
+ (getToken as jest.Mock).mockResolvedValue(null);
+ await middleware(makeRequest('PATCH', '/api/admin/auth') as any, makeFetchEvent());
+ expect(NextResponse.json).toHaveBeenCalledWith({ error: 'Unauthorized' }, { status: 401 });
+ });
+
+ it('returns 403 for admin API calls from a user who is not the instance admin', async () => {
+ (getToken as jest.Mock).mockResolvedValue({ hasCompletedOnboarding: true, isInstanceAdmin: false });
+ await middleware(makeRequest('PATCH', '/api/admin/auth') as any, makeFetchEvent());
+ expect(NextResponse.json).toHaveBeenCalledWith(
+ { error: expect.any(String) },
+ { status: 403 }
+ );
+ expect(NextResponse.next).not.toHaveBeenCalled();
+ });
+
+ it('rejects API keys on admin API routes', async () => {
+ await middleware(
+ makeRequest('GET', '/api/admin/auth', '', { Authorization: 'Bearer key-1' }) as any,
+ makeFetchEvent()
+ );
+ expect(NextResponse.json).toHaveBeenCalledWith({ error: 'Forbidden' }, { status: 403 });
+ });
+
+ it('passes admin API calls from the instance admin through to the route', async () => {
+ (getToken as jest.Mock).mockResolvedValue({ hasCompletedOnboarding: true, isInstanceAdmin: true });
+ await middleware(makeRequest('GET', '/api/admin/auth') as any, makeFetchEvent());
+ expect(NextResponse.next).toHaveBeenCalled();
+ expect(NextResponse.json).not.toHaveBeenCalled();
+ });
+ });
+
describe('withAuth callbacks.authorized', () => {
it('is called by withAuth and always returns true', async () => {
const capturedOpts = (withAuth as jest.Mock).mock.calls[0]?.[1];
diff --git a/src/client/src/__tests__/middleware/middleware.test.ts b/src/client/src/__tests__/middleware/middleware.test.ts
index 8734ade3..23f9bc14 100644
--- a/src/client/src/__tests__/middleware/middleware.test.ts
+++ b/src/client/src/__tests__/middleware/middleware.test.ts
@@ -40,6 +40,11 @@ describe('middleware', () => {
expect(config.matcher).toContain('/api/:path*');
});
+ it('matcher includes the instance admin area', () => {
+ expect(config.matcher).toContain('/admin');
+ expect(config.matcher).toContain('/admin/:path*');
+ });
+
it('matcher includes /login route', () => {
expect(config.matcher).toContain('/login');
});
diff --git a/src/client/src/app/(admin)/admin/page.tsx b/src/client/src/app/(admin)/admin/page.tsx
new file mode 100644
index 00000000..e459de31
--- /dev/null
+++ b/src/client/src/app/(admin)/admin/page.tsx
@@ -0,0 +1,27 @@
+import { redirect } from "next/navigation";
+import { ShieldCheck } from "lucide-react";
+import getMessage from "@/constants/messages";
+import { ICON_CLASSES } from "@/constants/sidebar";
+import { getAdminSidebarItems } from "@/features/admin-sidebar";
+
+export const dynamic = "force-dynamic";
+
+export default function AdminIndexPage() {
+ const first = getAdminSidebarItems(ICON_CLASSES).find((item) => item.link);
+ if (first?.link) redirect(first.link);
+
+ const messages = getMessage();
+ return (
+ <div className="flex h-full w-full flex-1 items-center justify-center p-6">
+ <div className="flex max-w-sm flex-col items-center gap-2 text-center">
+ <ShieldCheck className="size-6 text-stone-400 dark:text-stone-500" />
+ <h1 className="text-sm font-semibold text-stone-950 dark:text-stone-50">
+ {messages.INSTANCE_ADMIN_EMPTY_TITLE}
+ </h1>
+ <p className="text-xs text-stone-500 dark:text-stone-400">
+ {messages.INSTANCE_ADMIN_EMPTY_DESCRIPTION}
+ </p>
+ </div>
+ </div>
+ );
+}
diff --git a/src/client/src/app/(admin)/layout.tsx b/src/client/src/app/(admin)/layout.tsx
new file mode 100644
index 00000000..80a3e5da
--- /dev/null
+++ b/src/client/src/app/(admin)/layout.tsx
@@ -0,0 +1,35 @@
+import { redirect } from "next/navigation";
+import AdminShell from "@/components/(admin)/admin-shell";
+import CustomPostHogProvider from "@/components/(playground)/posthog";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { DEFAULT_LOGGED_IN_ROUTE, INSTANCE_ADMIN_ROUTE_PREFIX } from "@/constants/route";
+import { isInstanceAdminUser } from "@/lib/instance-admin";
+import { getCurrentUser } from "@/lib/session";
+
+export const dynamic = "force-dynamic";
+
+// Instance admin pages sit outside organisation and project scope. Middleware
+// filters on the session claim; this re-checks the database on every render.
+export default async function AdminLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ const user = await getCurrentUser();
+ if (!user) {
+ redirect(`/login?callbackUrl=${encodeURIComponent(INSTANCE_ADMIN_ROUTE_PREFIX)}`);
+ }
+ if (!(await isInstanceAdminUser(user.id))) {
+ redirect(DEFAULT_LOGGED_IN_ROUTE);
+ }
+
+ const telemetryEnabled = process.env.TELEMETRY_ENABLED !== "false";
+
+ return (
+ <CustomPostHogProvider telemetryEnabled={telemetryEnabled}>
+ <TooltipProvider>
+ <AdminShell adminEmail={user.email}>{children}</AdminShell>
+ </TooltipProvider>
+ </CustomPostHogProvider>
+ );
+}
diff --git a/src/client/src/app/api/admin/auth/route.ts b/src/client/src/app/api/admin/auth/route.ts
new file mode 100644
index 00000000..426f9970
--- /dev/null
+++ b/src/client/src/app/api/admin/auth/route.ts
@@ -0,0 +1,3 @@
+export const dynamic = "force-dynamic";
+
+export { GET, PATCH } from "@/lib/instance-env/http";
diff --git a/src/client/src/app/api/admin/auth/verify/route.ts b/src/client/src/app/api/admin/auth/verify/route.ts
new file mode 100644
index 00000000..81869c50
--- /dev/null
+++ b/src/client/src/app/api/admin/auth/verify/route.ts
@@ -0,0 +1,3 @@
+export const dynamic = "force-dynamic";
+
+export { VERIFY as POST } from "@/lib/instance-env/http";
diff --git a/src/client/src/app/api/organisation/[id]/overview/filters/route.ts b/src/client/src/app/api/organisation/[id]/overview/filters/route.ts
new file mode 100644
index 00000000..c04204e2
--- /dev/null
+++ b/src/client/src/app/api/organisation/[id]/overview/filters/route.ts
@@ -0,0 +1,7 @@
+import { disabledFeature } from "@/features/disabled-feature";
+
+const FEATURE_ID = "enterprise.organisation-overview";
+
+export function POST() {
+ return disabledFeature(FEATURE_ID).upgradeRequired();
+}
diff --git a/src/client/src/app/api/organisation/[id]/overview/route.ts b/src/client/src/app/api/organisation/[id]/overview/route.ts
new file mode 100644
index 00000000..c04204e2
--- /dev/null
+++ b/src/client/src/app/api/organisation/[id]/overview/route.ts
@@ -0,0 +1,7 @@
+import { disabledFeature } from "@/features/disabled-feature";
+
+const FEATURE_ID = "enterprise.organisation-overview";
+
+export function POST() {
+ return disabledFeature(FEATURE_ID).upgradeRequired();
+}
diff --git a/src/client/src/app/api/organisation/[id]/spend-limits/route.ts b/src/client/src/app/api/organisation/[id]/spend-limits/route.ts
new file mode 100644
index 00000000..c04204e2
--- /dev/null
+++ b/src/client/src/app/api/organisation/[id]/spend-limits/route.ts
@@ -0,0 +1,7 @@
+import { disabledFeature } from "@/features/disabled-feature";
+
+const FEATURE_ID = "enterprise.organisation-overview";
+
+export function POST() {
+ return disabledFeature(FEATURE_ID).upgradeRequired();
+}
diff --git a/src/client/src/app/auth.ts b/src/client/src/app/auth.ts
index 1be25add..45edf03f 100644
--- a/src/client/src/app/auth.ts
+++ b/src/client/src/app/auth.ts
@@ -1,9 +1,16 @@
import NextAuth, { AuthOptions } from "next-auth";
-import GoogleProvider from "next-auth/providers/google";
-import GithubProvider from "next-auth/providers/github";
+import type { NextRequest } from "next/server";
import CredentialsProvider from "next-auth/providers/credentials";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";
+import {
+ buildOAuthProviders,
+ emailFromProfile,
+ isEmailExplicitlyUnverified,
+ isEmailVouched,
+ OAUTH_LINK_PROVIDERS,
+ oauthProfilePatch,
+} from "@/lib/auth/oauth-providers";
import asaw from "@/utils/asaw";
import {
createNewUser,
@@ -12,20 +19,42 @@ import {
doesPasswordMatches,
getUserById,
} from "@/lib/user";
+import { isInstanceAdminUser } from "@/lib/instance-admin";
const prisma = new PrismaClient();
+// Invitations and shared database configs are addressed by email, so a new
+// account only claims them when its provider vouched for that email.
+async function claimEmailGrants(email: string, userId: string) {
+ try {
+ const { moveSharedDBConfigToDBUser } = await import("@/lib/db-config");
+ await moveSharedDBConfigToDBUser(email, userId);
+
+ const { moveInvitationsToMembership } = await import("@/lib/organisation");
+ await moveInvitationsToMembership(email, userId);
+ } catch (error) {
+ console.error("Error during new user setup:", error);
+ }
+}
+
// Create a custom adapter that normalizes emails
function createNormalizedEmailAdapter(p: PrismaClient) {
const baseAdapter = PrismaAdapter(p);
return {
...baseAdapter,
async createUser(user: any) {
- // Normalize email before creating user
- if (user.email) {
- user.email = user.email.toLowerCase().trim();
+ // next-auth passes the whole provider profile. Keep only User columns;
+ // provider-specific fields such as emailTrusted are not stored.
+ const created = await baseAdapter.createUser!({
+ name: user.name ?? null,
+ email: typeof user.email === "string" ? user.email.toLowerCase().trim() : user.email,
+ image: user.image ?? null,
+ emailVerified: user.emailVerified ?? null,
+ });
+ if (user.emailVouched === true && created.email && created.id) {
+ await claimEmailGrants(created.email, created.id);
}
- return baseAdapter.createUser!(user);
+ return created;
},
async getUserByEmail(email: string) {
// Normalize email before lookup
@@ -61,6 +90,7 @@ export const authOptions = {
// Update hasCompletedOnboarding status from database
token.hasCompletedOnboarding = existingUser.hasCompletedOnboarding;
+ token.isInstanceAdmin = await isInstanceAdminUser(existingUser.id);
} catch (error) {
console.error("Database error during JWT update:", error);
}
@@ -81,6 +111,7 @@ export const authOptions = {
// Update hasCompletedOnboarding status on every token refresh
token.hasCompletedOnboarding = existingUser.hasCompletedOnboarding;
+ token.isInstanceAdmin = await isInstanceAdminUser(existingUser.id);
} catch (error) {
// If there's a database connection error during startup,
// allow the token to pass through to avoid blocking the app
@@ -100,6 +131,7 @@ export const authOptions = {
if (existingUser) {
// Use the value from database (handles OAuth logins correctly)
token.hasCompletedOnboarding = existingUser.hasCompletedOnboarding;
+ token.isInstanceAdmin = await isInstanceAdminUser(existingUser.id);
} else {
// Fallback for brand new users (credentials provider during registration)
token.hasCompletedOnboarding = (user as any).hasCompletedOnboarding ?? false;
@@ -114,29 +146,48 @@ export const authOptions = {
return token;
},
signIn: async ({ user, account, profile }) => {
+ if (!user.email) {
+ const candidate = emailFromProfile(profile);
+ if (candidate) user.email = candidate;
+ }
+
if (!user.email) {
return false;
}
- // For Google provider, handle account linking
- if (account?.provider === "google" || account?.provider === "github") {
+ if (account?.provider && OAUTH_LINK_PROVIDERS.has(account.provider)) {
+ // A provider that says the email is unverified cannot claim it.
+ if (isEmailExplicitlyUnverified(profile)) {
+ return "/login?error=AccessDenied";
+ }
+ const emailVouched = isEmailVouched(account.provider, profile, user);
+ // Read by the adapter when this sign-in creates a new account.
+ (user as { emailVouched?: boolean }).emailVouched = emailVouched;
+
const [, existingUser] = await asaw(
getUserByEmail({ email: user.email })
);
- // If user exists but doesn't have Google account linked
+ // If user exists but doesn't have this provider linked yet
if (existingUser) {
+ const linkedAccount = await prisma.account.findFirst({
+ where: {
+ provider: account.provider,
+ providerAccountId: account.providerAccountId,
+ },
+ select: { userId: true },
+ });
+ // An identity linked to another account never signs in as this one.
+ if (linkedAccount && linkedAccount.userId !== existingUser.id) {
+ return "/login?error=OAuthAccountNotLinked";
+ }
+ // Linking a new identity by email needs a provider-verified email.
+ // An identity already linked to this account can always sign in.
+ if (!linkedAccount && !emailVouched) {
+ return "/login?error=OAuthAccountNotLinked";
+ }
try {
- // Check if Provider's account is already linked
- const existingAccount = await prisma.account.findFirst({
- where: {
- userId: existingUser.id,
- provider: account?.provider
- }
- });
-
- // If Provider's account not linked, link it manually
- if (!existingAccount) {
+ if (!linkedAccount) {
await prisma.account.create({
data: {
userId: existingUser.id,
@@ -155,19 +206,10 @@ export const authOptions = {
// Update user info if name/image is missing
if (!existingUser.name || !existingUser.image) {
+ const patch = oauthProfilePatch(account.provider, profile);
const updateData: { name?: string; image?: string } = {};
-
- // Handle different profile structures for different providers
- if (account.provider === "google") {
- updateData.name = profile?.name || existingUser.name;
- // @ts-ignore - this is a bug in the types, `picture` is a valid on the `Profile` type
- updateData.image = profile?.picture || existingUser.image;
- } else if (account.provider === "github") {
- // @ts-ignore - this is a bug in the types, `login` is a valid on the `Profile` type
- updateData.name = profile?.name || profile?.login || existingUser.name;
- // @ts-ignore - this is a bug in the types, `avatar_url` is a valid on the `Profile` type
- updateData.image = profile?.avatar_url || existingUser.image;
- }
+ if (!existingUser.name && patch.name) updateData.name = patch.name;
+ if (!existingUser.image && patch.image) updateData.image = patch.image;
if (Object.keys(updateData).length > 0) {
await asaw(
@@ -195,48 +237,14 @@ export const authOptions = {
async session({ session, token }: { session: any; token: any }) {
try {
session.user.id = token.id;
+ session.user.isInstanceAdmin = token.isInstanceAdmin === true;
} catch (e) {
console.log(e);
}
return session;
},
},
- events: {
- async createUser({ user }) {
- // Run custom setup for new users
- if (user.email && user.id) {
- try {
- // Normalize email for consistency
- const normalizedEmail = user.email.toLowerCase().trim();
-
- const { moveSharedDBConfigToDBUser } = await import("@/lib/db-config");
- await moveSharedDBConfigToDBUser(normalizedEmail, user.id);
-
- const { moveInvitationsToMembership } = await import("@/lib/organisation");
- await moveInvitationsToMembership(normalizedEmail, user.id);
- } catch (error) {
- console.error("Error during new user setup:", error);
- }
- }
- }
- },
providers: [
- ...(process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET
- ? [
- GoogleProvider({
- clientId: process.env.GOOGLE_CLIENT_ID,
- clientSecret: process.env.GOOGLE_CLIENT_SECRET,
- }),
- ]
- : []),
- ...(process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET
- ? [
- GithubProvider({
- clientId: process.env.GITHUB_CLIENT_ID,
- clientSecret: process.env.GITHUB_CLIENT_SECRET,
- }),
- ]
- : []),
CredentialsProvider({
id: "login",
name: "Credentials Login",
@@ -296,6 +304,19 @@ export const authOptions = {
session: { strategy: "jwt" },
} as AuthOptions;
-const handler = NextAuth(authOptions);
+async function buildAuthOptions(): Promise<AuthOptions> {
+ const oauthProviders = await buildOAuthProviders();
+ return {
+ ...authOptions,
+ providers: [...oauthProviders, ...authOptions.providers],
+ };
+}
+
+async function handler(
+ req: NextRequest,
+ context: { params: { nextauth: string[] } }
+) {
+ return NextAuth(req, context, await buildAuthOptions());
+}
export { handler as GET, handler as POST };
\ No newline at end of file
diff --git a/src/client/src/components/(admin)/admin-shell.tsx b/src/client/src/components/(admin)/admin-shell.tsx
new file mode 100644
index 00000000..48c0a8ec
--- /dev/null
+++ b/src/client/src/components/(admin)/admin-shell.tsx
@@ -0,0 +1,204 @@
+"use client";
+
+import type { ReactNode } from "react";
+import Link from "next/link";
+import { usePathname } from "next/navigation";
+import { signOut } from "next-auth/react";
+import { ArrowLeft, LogOut, ShieldCheck } from "lucide-react";
+import SidebarBrand from "@/components/(playground)/sidebar-brand";
+import {
+ SidebarLayoutProvider,
+ playgroundTopBarClassName,
+ useSidebarLayout,
+} from "@/components/(playground)/sidebar-layout-context";
+import { HeaderScopeSeparator } from "@/components/(playground)/header-scope-pill";
+import ThemeToggleSwitch from "@/components/(playground)/sidebar/theme-switch";
+import { Button } from "@/components/ui/button";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import getMessage from "@/constants/messages";
+import { DEFAULT_LOGGED_IN_ROUTE } from "@/constants/route";
+import { ICON_CLASSES } from "@/constants/sidebar";
+import { getAdminSidebarItems } from "@/features/admin-sidebar";
+import { cn } from "@/lib/utils";
+
+const NAV_LINK_CLASS =
+ "flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-[13px] font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-stone-950 focus-visible:ring-offset-2 focus-visible:ring-offset-white dark:focus-visible:ring-stone-300 dark:focus-visible:ring-offset-stone-950";
+const NAV_LINK_ACTIVE_CLASS = "bg-stone-200 text-stone-950 dark:bg-stone-800 dark:text-white";
+const NAV_LINK_IDLE_CLASS =
+ "text-stone-600 hover:bg-stone-200/70 hover:text-stone-950 dark:text-stone-300 dark:hover:bg-stone-800 dark:hover:text-white";
+
+function AdminNavLink({
+ href,
+ icon,
+ text,
+ active,
+ compact,
+}: {
+ href: string;
+ icon?: ReactNode;
+ text: string;
+ active: boolean;
+ compact: boolean;
+}) {
+ const link = (
+ <Link
+ href={href}
+ aria-current={active ? "page" : undefined}
+ className={cn(
+ NAV_LINK_CLASS,
+ compact && "justify-center px-2",
+ active ? NAV_LINK_ACTIVE_CLASS : NAV_LINK_IDLE_CLASS
+ )}
+ >
+ {icon}
+ <span className={cn("min-w-0 truncate", compact && "sr-only")}>{text}</span>
+ </Link>
+ );
+ if (!compact) return link;
+ return (
+ <Tooltip delayDuration={100}>
+ <TooltipTrigger asChild>{link}</TooltipTrigger>
+ <TooltipContent side="right" sideOffset={8}>
+ {text}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+function AdminSidebar({ adminEmail }: { adminEmail: string }) {
+ const messages = getMessage();
+ const pathname = usePathname() || "";
+ const { isExpanded } = useSidebarLayout();
+ const compact = !isExpanded;
+ const items = getAdminSidebarItems(ICON_CLASSES).filter((item) => item.link);
+
+ return (
+ <aside
+ aria-label={messages.INSTANCE_ADMIN_NAVIGATION}
+ className="flex h-full min-h-0 w-full flex-col bg-stone-50 dark:bg-stone-950"
+ >
+ <nav
+ aria-label={messages.INSTANCE_ADMIN_NAVIGATION}
+ className="scrollbar-hidden flex grow flex-col gap-1 overflow-y-auto px-2 py-3"
+ >
+ {!compact ? (
+ <p className="px-2.5 pb-1 text-xs font-semibold tracking-wide text-stone-500 dark:text-stone-400">
+ {messages.INSTANCE_ADMIN_NAVIGATION}
+ </p>
+ ) : null}
+ {items.map((item) => (
+ <AdminNavLink
+ key={item.link}
+ href={item.link!}
+ icon={item.icon}
+ text={item.text}
+ active={pathname === item.link || pathname.startsWith(`${item.link}/`)}
+ compact={compact}
+ />
+ ))}
+ </nav>
+ <div className="flex flex-col gap-1 border-t border-stone-200 p-2 dark:border-stone-800">
+ <AdminNavLink
+ href={DEFAULT_LOGGED_IN_ROUTE}
+ icon={<ArrowLeft className={ICON_CLASSES} />}
+ text={messages.INSTANCE_ADMIN_BACK_TO_APP}
+ active={false}
+ compact={compact}
+ />
+ {!compact ? (
+ <div className="flex items-center justify-between gap-2 px-2.5 py-1.5">
+ <div className="grid min-w-0 text-left leading-tight">
+ <span className="text-[11px] text-stone-500 dark:text-stone-400">
+ {messages.INSTANCE_ADMIN_SIGNED_IN_AS}
+ </span>
+ <span className="truncate text-xs font-medium text-stone-700 dark:text-stone-200">
+ {adminEmail}
+ </span>
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ aria-label={messages.LOG_OUT}
+ title={messages.LOG_OUT}
+ onClick={() => signOut({ callbackUrl: "/login" })}
+ className="size-8 shrink-0 text-stone-600 hover:bg-stone-200 dark:text-stone-300 dark:hover:bg-stone-800"
+ >
+ <LogOut className="size-4" />
+ </Button>
+ </div>
+ ) : null}
+ </div>
+ </aside>
+ );
+}
+
+function AdminShellFrame({
+ adminEmail,
+ children,
+}: {
+ adminEmail: string;
+ children: ReactNode;
+}) {
+ const messages = getMessage();
+ const { sidebarWidthClass } = useSidebarLayout();
+
+ return (
+ <div className="flex h-screen w-full flex-col overflow-hidden border border-stone-200 bg-stone-50 dark:border-stone-800 dark:bg-stone-950">
+ <div className="flex shrink-0 border-b border-stone-200 dark:border-stone-800">
+ <div
+ className={cn(
+ "relative shrink-0 border-r border-stone-200 dark:border-stone-800",
+ sidebarWidthClass
+ )}
+ >
+ <SidebarBrand />
+ </div>
+ <header
+ className={playgroundTopBarClassName("min-w-0 flex-1 gap-3 pl-6 pr-3")}
+ >
+ <div className="flex min-w-0 items-center gap-2 text-stone-950 dark:text-white">
+ <ShieldCheck className="size-4 shrink-0 text-stone-500 dark:text-stone-400" />
+ <span className="truncate text-[13px] font-semibold">
+ {messages.INSTANCE_ADMIN_TITLE}
+ </span>
+ </div>
+ <HeaderScopeSeparator />
+ <span className="truncate text-xs text-stone-500 dark:text-stone-400">
+ {adminEmail}
+ </span>
+ <div className="ml-auto flex items-center gap-2">
+ <ThemeToggleSwitch />
+ </div>
+ </header>
+ </div>
+ <div className="flex min-h-0 flex-1">
+ <div
+ className={cn(
+ "relative z-30 flex shrink-0 flex-col border-r border-stone-200 dark:border-stone-800",
+ sidebarWidthClass
+ )}
+ >
+ <AdminSidebar adminEmail={adminEmail} />
+ </div>
+ <main className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
+ {children}
+ </main>
+ </div>
+ </div>
+ );
+}
+
+export default function AdminShell({
+ adminEmail,
+ children,
+}: {
+ adminEmail: string;
+ children: ReactNode;
+}) {
+ return (
+ <SidebarLayoutProvider>
+ <AdminShellFrame adminEmail={adminEmail}>{children}</AdminShellFrame>
+ </SidebarLayoutProvider>
+ );
+}
diff --git a/src/client/src/components/(admin)/instance-auth-page.tsx b/src/client/src/components/(admin)/instance-auth-page.tsx
new file mode 100644
index 00000000..0264270f
--- /dev/null
+++ b/src/client/src/components/(admin)/instance-auth-page.tsx
@@ -0,0 +1,3 @@
+export default function InstanceAuthPage() {
+ return null;
+}
diff --git a/src/client/src/components/(auth)/auth-form.tsx b/src/client/src/components/(auth)/auth-form.tsx
index 23f57c3c..40457e35 100644
--- a/src/client/src/components/(auth)/auth-form.tsx
+++ b/src/client/src/components/(auth)/auth-form.tsx
@@ -9,9 +9,22 @@ import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { Loader2 } from "lucide-react";
import { usePostHog } from "posthog-js/react";
import { CLIENT_EVENTS } from "@/constants/events";
import getMessage from "@/constants/messages";
+import {
+ GithubMark,
+ GoogleMark,
+ MicrosoftMark,
+ OktaMark,
+} from "@/components/(auth)/provider-marks";
const getErrors = () => {
const m = getMessage();
@@ -45,8 +58,7 @@ export function AuthForm({ type }: { type: "login" | "register" }) {
(searchParams.get("callbackUrl") as string) || DEFAULT_LOGGED_IN_ROUTE;
const errorType: string = (searchParams.get("error") as string);
const [error, setError] = useState<string>(errorType || "");
- const [isGoogleLoading, setIsGoogleLoading] = useState(false);
- const [isGithubLoading, setIsGithubLoading] = useState(false);
+ const [pendingProvider, setPendingProvider] = useState<string | null>(null);
const [providers, setProviders] = useState<string[]>([]);
const m = getMessage();
@@ -79,47 +91,44 @@ export function AuthForm({ type }: { type: "login" | "register" }) {
window.location.replace(callbackUrl);
}
- async function handleGoogleSignIn() {
- setIsGoogleLoading(true);
- setError("");
-
- try {
- const result = await signIn("google", {
- callbackUrl,
- redirect: false,
- });
+ const oauthButtons = [
+ {
+ id: "google",
+ label: m.AUTH_CONTINUE_WITH_GOOGLE,
+ error: m.AUTH_ERROR_GOOGLE,
+ icon: <GoogleMark className="size-5" />,
+ },
+ {
+ id: "github",
+ label: m.AUTH_CONTINUE_WITH_GITHUB,
+ error: m.AUTH_ERROR_GITHUB,
+ icon: <GithubMark className="size-5" />,
+ },
+ {
+ id: "azure-ad",
+ label: m.AUTH_CONTINUE_WITH_MICROSOFT,
+ error: m.AUTH_ERROR_MICROSOFT,
+ icon: <MicrosoftMark className="size-5" />,
+ },
+ {
+ id: "okta",
+ label: m.AUTH_CONTINUE_WITH_OKTA,
+ error: m.AUTH_ERROR_OKTA,
+ icon: <OktaMark className="size-5" />,
+ },
+ ];
- if (result?.error) {
- console.error("Google sign-in error:", result.error);
- setError(result.error);
- }
- } catch (err) {
- console.error("Google sign-in exception:", err);
- setError(m.AUTH_ERROR_GOOGLE);
- } finally {
- setIsGoogleLoading(false);
- }
- }
-
- async function handleGithubSignIn() {
- setIsGithubLoading(true);
+ async function handleOAuthSignIn(provider: { id: string; error: string }) {
+ setPendingProvider(provider.id);
setError("");
try {
- const result = await signIn("github", {
- callbackUrl,
- redirect: false,
- });
-
- if (result?.error) {
- console.error("Github sign-in error:", result.error);
- setError(result.error);
- }
- } catch (err) {
- console.error("Github sign-in exception:", err);
- setError(m.AUTH_ERROR_GITHUB);
- } finally {
- setIsGithubLoading(false);
+ // OAuth providers always send the browser to the provider's sign-in page.
+ await signIn(provider.id, { callbackUrl });
+ } catch {
+ console.error("OAuth sign-in exception:", provider.id);
+ setError(provider.error);
+ setPendingProvider(null);
}
}
@@ -149,61 +158,36 @@ export function AuthForm({ type }: { type: "login" | "register" }) {
<div className="grid w-full gap-6 text-stone-900 dark:text-stone-100">
{error && <SignInError error={error} />}
- {/* Google Sign-in Button */}
- {providers.includes("google") && (
- <Button
- type="button"
- variant="outline"
- onClick={handleGoogleSignIn}
- disabled={isGoogleLoading}
- className="w-full bg-white dark:bg-stone-900 text-stone-900 dark:text-stone-100 border-stone-200 dark:border-stone-700 hover:bg-stone-50 dark:hover:bg-stone-800 rounded-md hover:text-stone-900 dark:hover:text-stone-100"
- >
- {isGoogleLoading ? (
- m.AUTH_SIGNING_IN
- ) : (
- <div className="flex items-center justify-center gap-2">
- <svg
- className="w-4 h-4"
- viewBox="0 0 24 24"
- xmlns="http://www.w3.org/2000/svg"
- >
- <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
- <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
- <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
- <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
- </svg>
- {m.AUTH_CONTINUE_WITH_GOOGLE}
- </div>
- )}
- </Button>
- )}
-
- {providers.includes("github") && (
- <Button
- type="button"
- variant="outline"
- onClick={handleGithubSignIn}
- disabled={isGithubLoading}
- className="w-full bg-white dark:bg-stone-900 text-stone-900 dark:text-stone-100 border-stone-200 dark:border-stone-700 hover:bg-stone-50 dark:hover:bg-stone-800 rounded-md hover:text-stone-900 dark:hover:text-stone-100"
- >
- {isGithubLoading ? (
- m.AUTH_SIGNING_IN
- ) : (
- <div className="flex items-center justify-center gap-2">
- <svg
- className="w-4 h-4"
- viewBox="0 0 24 24"
- xmlns="http://www.w3.org/2000/svg"
- >
- <path
- fill="currentColor"
- d="M12 0C5.374 0 0 5.373 0 12c0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23A11.509 11.509 0 0112 5.803c1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576C20.566 21.797 24 17.3 24 12c0-6.627-5.373-12-12-12z"
- />
- </svg>
- {m.AUTH_CONTINUE_WITH_GITHUB}
- </div>
- )}
- </Button>
+ {providers.length > 0 && (
+ <TooltipProvider>
+ <div className="flex flex-wrap items-center justify-center gap-3">
+ {oauthButtons.filter((provider) => providers.includes(provider.id)).map((provider) => (
+ <Tooltip key={provider.id} delayDuration={100}>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ aria-label={provider.label}
+ aria-busy={pendingProvider === provider.id}
+ onClick={() => handleOAuthSignIn(provider)}
+ disabled={pendingProvider !== null}
+ className="size-11 rounded-md border-stone-200 bg-white text-stone-900 hover:bg-stone-50 hover:text-stone-900 dark:border-stone-700 dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800 dark:hover:text-stone-100"
+ >
+ {pendingProvider === provider.id ? (
+ <Loader2 className="size-5 animate-spin" aria-hidden="true" />
+ ) : (
+ provider.icon
+ )}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="text-xs">
+ {provider.label}
+ </TooltipContent>
+ </Tooltip>
+ ))}
+ </div>
+ </TooltipProvider>
)}
{/* Divider */}
diff --git a/src/client/src/components/(auth)/provider-marks.tsx b/src/client/src/components/(auth)/provider-marks.tsx
new file mode 100644
index 00000000..c688abd0
--- /dev/null
+++ b/src/client/src/components/(auth)/provider-marks.tsx
@@ -0,0 +1,43 @@
+// Brand marks for the OAuth sign-in providers, shared by sign-in and admin pages.
+
+export function GoogleMark({ className = "size-4" }: { className?: string }) {
+ return (
+ <svg className={className} viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
+ <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
+ <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
+ <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
+ <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
+ </svg>
+ );
+}
+
+export function GithubMark({ className = "size-4" }: { className?: string }) {
+ return (
+ <svg className={className} viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
+ <path
+ fill="currentColor"
+ d="M12 0C5.374 0 0 5.373 0 12c0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23A11.509 11.509 0 0112 5.803c1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576C20.566 21.797 24 17.3 24 12c0-6.627-5.373-12-12-12z"
+ />
+ </svg>
+ );
+}
+
+export function MicrosoftMark({ className = "size-4" }: { className?: string }) {
+ return (
+ <svg className={className} viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
+ <path fill="#F25022" d="M1 1h10.5v10.5H1z" />
+ <path fill="#7FBA00" d="M12.5 1H23v10.5H12.5z" />
+ <path fill="#00A4EF" d="M1 12.5h10.5V23H1z" />
+ <path fill="#FFB900" d="M12.5 12.5H23V23H12.5z" />
+ </svg>
+ );
+}
+
+export function OktaMark({ className = "size-4" }: { className?: string }) {
+ return (
+ <svg className={className} viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
+ <circle cx="12" cy="12" r="10" fill="none" stroke="currentColor" strokeWidth="2.5" />
+ <circle cx="12" cy="12" r="4" fill="currentColor" />
+ </svg>
+ );
+}
diff --git a/src/client/src/components/(playground)/organisation/organisation-overview-license-card.tsx b/src/client/src/components/(playground)/organisation/organisation-overview-license-card.tsx
new file mode 100644
index 00000000..638fe2cb
--- /dev/null
+++ b/src/client/src/components/(playground)/organisation/organisation-overview-license-card.tsx
@@ -0,0 +1,25 @@
+"use client";
+
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import getMessage from "@/constants/messages";
+import { Sparkles } from "lucide-react";
+
+export default function OrganisationOverviewLicenseCard() {
+ const messages = getMessage();
+
+ return (
+ <Card className="border-stone-200 dark:border-stone-800">
+ <CardHeader className="pb-2">
+ <CardTitle className="flex items-center gap-2 text-base text-stone-950 dark:text-stone-50">
+ <Sparkles className="h-4 w-4 text-primary" />
+ {messages.ORGANISATION_OVERVIEW_LICENSE_TITLE}
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ <p className="text-sm leading-6 text-stone-600 dark:text-stone-300">
+ {messages.ORGANISATION_OVERVIEW_LICENSE_DESCRIPTION}
+ </p>
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/src/client/src/components/(playground)/organisation/organisation-page.tsx b/src/client/src/components/(playground)/organisation/organisation-page.tsx
index b6129a33..f02b1792 100644
--- a/src/client/src/components/(playground)/organisation/organisation-page.tsx
+++ b/src/client/src/components/(playground)/organisation/organisation-page.tsx
@@ -51,6 +51,7 @@ import {
FolderKanban,
Database,
Plus,
+ LayoutDashboard,
} from "lucide-react";
import { useRootStore } from "@/store";
import {
@@ -96,6 +97,7 @@ import { cn } from "@/lib/utils";
import getMessage from "@/constants/messages";
import { escapeEmailForDisplay } from "@/utils/string";
import { toast } from "sonner";
+import OrganisationOverviewLicenseCard from "@/components/(playground)/organisation/organisation-overview-license-card";
interface Member {
id: string;
@@ -152,13 +154,13 @@ export default function OrganisationSettingsPage() {
const isProjectsRoute = pathname === "/organisation/projects";
const requestedTab = isProjectsRoute
? "projects"
- : searchParams.get("tab") || "details";
+ : searchParams.get("tab") || "overview";
const availableTabs = orgPendingInvites.length > 0
- ? ["details", "projects", "members", "pending"]
- : ["details", "projects", "members"];
+ ? ["overview", "details", "projects", "members", "pending"]
+ : ["overview", "details", "projects", "members"];
const selectedTab = availableTabs.includes(requestedTab)
? requestedTab
- : "details";
+ : "overview";
const handleTabChange = (tab: string) => {
if (tab === "projects") {
router.replace("/organisation/projects", { scroll: false });
@@ -167,7 +169,7 @@ export default function OrganisationSettingsPage() {
const params = new URLSearchParams(searchParams.toString());
params.delete("tab");
- if (tab !== "details") {
+ if (tab !== "overview") {
params.set("tab", tab);
}
const query = params.toString();
@@ -381,6 +383,11 @@ export default function OrganisationSettingsPage() {
{currentOrg ? (
<div className="flex flex-wrap items-center gap-2">
{[
+ {
+ key: "overview",
+ label: messages.ORGANISATION_OVERVIEW,
+ icon: LayoutDashboard,
+ },
{ key: "details", label: messages.DETAILS, icon: Settings },
{
key: "projects",
@@ -479,6 +486,9 @@ export default function OrganisationSettingsPage() {
{currentOrg && (
<Tabs value={selectedTab} onValueChange={handleTabChange} className="w-full mt-4">
+ <TabsContent value="overview" className="mt-0">
+ <OrganisationOverviewLicenseCard />
+ </TabsContent>
<TabsContent value="details" className="space-y-4 mt-0">
{hasAdminPermissions ? (
diff --git a/src/client/src/components/(playground)/sidebar/user-actions.tsx b/src/client/src/components/(playground)/sidebar/user-actions.tsx
index 034292ea..ccb13445 100644
--- a/src/client/src/components/(playground)/sidebar/user-actions.tsx
+++ b/src/client/src/components/(playground)/sidebar/user-actions.tsx
@@ -3,13 +3,15 @@ import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { getUserDetails, resetUser } from "@/selectors/user";
import { useRootStore } from "@/store";
-import { ChevronsUpDown, Cog, LogOut, Pencil } from "lucide-react";
-import { signOut } from "next-auth/react";
+import { ChevronsUpDown, LogOut, Pencil, ShieldCheck } from "lucide-react";
+import { signOut, useSession } from "next-auth/react";
import Link from "next/link";
import { usePostHog } from "posthog-js/react";
import { useEffect } from "react";
import getMessage from "@/constants/messages";
import { escapeEmailForDisplay } from "@/utils/string";
+import { INSTANCE_ADMIN_ROUTE_PREFIX } from "@/constants/route";
+import { getAdminSidebarItems } from "@/features/admin-sidebar";
const DROPDOWN_MENU_ITEM_CLASS = "flex w-full text-[13px] gap-2 hover:bg-primary/10 dark:hover:bg-primary/10 px-2 py-1.5";
const DROPDOWN_MENU_ICON_CLASS = "w-4 h-4";
@@ -19,6 +21,10 @@ export default function UserActions() {
const messages = getMessage();
const user = useRootStore(getUserDetails);
const resetUserFn = useRootStore(resetUser);
+ const { data: session } = useSession();
+ const showInstanceAdmin =
+ (session?.user as { isInstanceAdmin?: boolean } | undefined)?.isInstanceAdmin === true &&
+ getAdminSidebarItems(DROPDOWN_MENU_ICON_CLASS).length > 0;
const onClickSignout = () => {
posthog?.reset();
resetUserFn();
@@ -75,6 +81,14 @@ export default function UserActions() {
{messages.EDIT_DETAILS}
</Link>
</DropdownMenuItem>
+ {showInstanceAdmin ? (
+ <DropdownMenuItem className="p-0">
+ <Link href={INSTANCE_ADMIN_ROUTE_PREFIX} className={DROPDOWN_MENU_ITEM_CLASS}>
+ <ShieldCheck className={DROPDOWN_MENU_ICON_CLASS} />
+ {messages.INSTANCE_ADMIN_TITLE}
+ </Link>
+ </DropdownMenuItem>
+ ) : null}
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem className="p-0" onClick={onClickSignout}>
diff --git a/src/client/src/constants/messages/en.ts b/src/client/src/constants/messages/en.ts
index b540424a..7567cec8 100644
--- a/src/client/src/constants/messages/en.ts
+++ b/src/client/src/constants/messages/en.ts
@@ -1675,6 +1675,11 @@ export const DANGER_ZONE = "Danger Zone";
export const DANGER_ZONE_DESCRIPTION = "Irreversible actions for this organisation";
export const GENERAL = "General";
export const DETAILS = "Details";
+export const ORGANISATION_OVERVIEW = "Overview";
+export const ORGANISATION_OVERVIEW_LICENSE_TITLE =
+ "Organisation overview is an enterprise feature";
+export const ORGANISATION_OVERVIEW_LICENSE_DESCRIPTION =
+ "See requests, cost, latency, errors, and tokens across every project in this organisation. Apply an enterprise license to open it.";
export const PENDING = "Pending";
export const NAME = "Name";
export const EMAIL = "Email";
@@ -1904,6 +1909,8 @@ export const TALK_TO_FOUNDER_HINT = "Schedule a 30-minute call";
export const AUTH_SIGNING_IN = "Signing in...";
export const AUTH_CONTINUE_WITH_GOOGLE = "Continue with Google";
export const AUTH_CONTINUE_WITH_GITHUB = "Continue with Github";
+export const AUTH_CONTINUE_WITH_MICROSOFT = "Continue with Microsoft";
+export const AUTH_CONTINUE_WITH_OKTA = "Continue with Okta";
export const AUTH_OR = "Or";
export const AUTH_EMAIL = "Email";
export const AUTH_EMAIL_PLACEHOLDER = "[email protected]";
@@ -1925,6 +1932,8 @@ export const AUTH_ERROR_CONFIGURATION = "There is a problem with the server conf
export const AUTH_ERROR_DEFAULT = "Unable to sign in.";
export const AUTH_ERROR_GOOGLE = "Failed to sign in with Google";
export const AUTH_ERROR_GITHUB = "Failed to sign in with Github";
+export const AUTH_ERROR_MICROSOFT = "Failed to sign in with Microsoft";
+export const AUTH_ERROR_OKTA = "Failed to sign in with Okta";
// Founder call sidebar card
export const FOUNDER_CARD_BADGE = "From the founder";
@@ -3388,3 +3397,14 @@ export const API_KEY_FULL_ACCESS_DESCRIPTION =
"Can use every feature that accepts API keys.";
export const API_KEY_DELETE = "Delete API key";
export const API_KEY_INVALID_JSON = "Request body must be valid JSON.";
+
+// Instance admin
+export const INSTANCE_ADMIN_TITLE = "Instance admin";
+export const INSTANCE_ADMIN_REQUIRED =
+ "Only the instance admin can manage instance settings.";
+export const INSTANCE_ADMIN_BACK_TO_APP = "Back to app";
+export const INSTANCE_ADMIN_SIGNED_IN_AS = "Signed in as";
+export const INSTANCE_ADMIN_NAVIGATION = "Instance settings";
+export const INSTANCE_ADMIN_EMPTY_TITLE = "No instance settings yet";
+export const INSTANCE_ADMIN_EMPTY_DESCRIPTION =
+ "Instance settings are not available in this edition.";
diff --git a/src/client/src/constants/route.ts b/src/client/src/constants/route.ts
index 6ad69fc7..2f9ac4be 100644
--- a/src/client/src/constants/route.ts
+++ b/src/client/src/constants/route.ts
@@ -91,3 +91,7 @@ export const RESTRICTED_DEMO_ACCOUNT_ROUTES: Record<string, string[]> = {
PUT: ["/api/db-config", "/api/vault"],
DELETE: ["/api/db-config", "/api/api-key", "/api/vault", "/api/prompt-hub"],
};
+
+// Instance admin area: its own shell outside organisation/project scope.
+export const INSTANCE_ADMIN_ROUTE_PREFIX = "/admin";
+export const INSTANCE_ADMIN_API_ROUTE_PREFIX = "/api/admin";
diff --git a/src/client/src/constants/sidebar.tsx b/src/client/src/constants/sidebar.tsx
index fd098e3f..9eef9803 100644
--- a/src/client/src/constants/sidebar.tsx
+++ b/src/client/src/constants/sidebar.tsx
@@ -181,6 +181,7 @@ export const SIDEBAR_ITEMS: SidebarItemProps[] = [
link: "/openapi-spec",
type: "action",
},
+ ...getEnterpriseSidebarItems("settings", ICON_CLASSES),
],
},
{
diff --git a/src/client/src/features/admin-sidebar.ts b/src/client/src/features/admin-sidebar.ts
new file mode 100644
index 00000000..3e269acf
--- /dev/null
+++ b/src/client/src/features/admin-sidebar.ts
@@ -0,0 +1,7 @@
+import { SidebarActionItem } from "@/types/sidebar";
+
+// Navigation for the instance admin area. Open source has no instance
+// settings pages yet; enterprise replaces this module with its own items.
+export function getAdminSidebarItems(_iconClasses: string): SidebarActionItem[] {
+ return [];
+}
diff --git a/src/client/src/features/sidebar.ts b/src/client/src/features/sidebar.ts
index 4d27ef4f..54158a43 100644
--- a/src/client/src/features/sidebar.ts
+++ b/src/client/src/features/sidebar.ts
@@ -1,6 +1,6 @@
import { SidebarActionItem } from "@/types/sidebar";
-export type EnterpriseSidebarSection = "monitoring" | "configuration";
+export type EnterpriseSidebarSection = "monitoring" | "configuration" | "settings";
export function getEnterpriseSidebarItems(
_section: EnterpriseSidebarSection,
diff --git a/src/client/src/lib/auth/oauth-providers.ts b/src/client/src/lib/auth/oauth-providers.ts
new file mode 100644
index 00000000..ed89c2f2
--- /dev/null
+++ b/src/client/src/lib/auth/oauth-providers.ts
@@ -0,0 +1,163 @@
+import type { AuthOptions } from "next-auth";
+import AzureADProvider from "next-auth/providers/azure-ad";
+import GithubProvider from "next-auth/providers/github";
+import GoogleProvider from "next-auth/providers/google";
+import OktaProvider from "next-auth/providers/okta";
+import { type InstanceEnvKey } from "@/lib/instance-env/catalog";
+import { loadInstanceEnvOverrides } from "@/lib/instance-env/store";
+import {
+ normalizeAzureTenant,
+ normalizeClientId,
+ normalizeOktaIssuer,
+ normalizeSecret,
+} from "@/lib/instance-env/values";
+import { resolvesToPublicHost } from "@/lib/instance-env/public-host";
+
+export const OAUTH_LINK_PROVIDERS = new Set(["google", "github", "azure-ad", "okta"]);
+
+const MULTI_TENANT_AZURE = new Set(["common", "organizations", "consumers"]);
+
+/**
+ * Whether the provider vouches for the email on this sign-in. Only a vouched
+ * email may be linked to an existing account; otherwise anyone able to set an
+ * email claim (for example an admin of any Microsoft Entra tenant when the app
+ * accepts all tenants) could sign in as that account.
+ */
+export function isEmailVouched(provider: string, profile: unknown, user?: unknown): boolean {
+ const record = profile && typeof profile === "object" ? (profile as Record<string, unknown>) : {};
+ switch (provider) {
+ case "google":
+ case "okta":
+ return record.email_verified === true || record.email_verified === "true";
+ case "github":
+ // GitHub only returns the account's own primary email.
+ return true;
+ case "azure-ad":
+ return Boolean(user && typeof user === "object" && (user as { emailTrusted?: unknown }).emailTrusted === true);
+ default:
+ return false;
+ }
+}
+
+/** True when the provider explicitly reports the email as unverified. */
+export function isEmailExplicitlyUnverified(profile: unknown): boolean {
+ const record = profile && typeof profile === "object" ? (profile as Record<string, unknown>) : {};
+ return record.email_verified === false || record.email_verified === "false";
+}
+
+export function emailFromProfile(profile: unknown): string | null {
+ if (!profile || typeof profile !== "object") return null;
+ const record = profile as Record<string, unknown>;
+ for (const key of ["email", "preferred_username", "upn"]) {
+ const value = record[key];
+ if (typeof value !== "string") continue;
+ const email = value.trim().toLowerCase();
+ if (!email.includes("@") || email.includes(" ") || email.length > 320) continue;
+ if (/[\u0000-\u001F\u007F]/.test(email)) continue;
+ return email;
+ }
+ return null;
+}
+
+export function oauthProfilePatch(provider: string, profile: unknown): { name?: string; image?: string } {
+ if (!profile || typeof profile !== "object") return {};
+ const record = profile as Record<string, unknown>;
+ const text = (value: unknown) => (typeof value === "string" ? value.trim() : "");
+ const name =
+ text(record.name) ||
+ (provider === "github" ? text(record.login) : "") ||
+ text(record.preferred_username);
+ const image = provider === "github" ? text(record.avatar_url) : text(record.picture);
+ const patch: { name?: string; image?: string } = {};
+ if (name) patch.name = name;
+ if (image) patch.image = image;
+ return patch;
+}
+
+function configuredValue(
+ overrides: Partial<Record<InstanceEnvKey, string>>,
+ key: InstanceEnvKey,
+ normalize: (value: string) => string | null
+) {
+ const override = overrides[key];
+ if (typeof override === "string" && override.trim()) return normalize(override);
+ const fromEnv = (process.env[key] || "").trim();
+ if (!fromEnv) return null;
+ return normalize(fromEnv);
+}
+
+function azureProfile(profile: Record<string, unknown>, emailTrusted: boolean) {
+ const email = emailFromProfile(profile);
+ const name = typeof profile.name === "string" ? profile.name : null;
+ const id = typeof profile.sub === "string" ? profile.sub : email || "azure-ad";
+ return {
+ id,
+ name,
+ email: email || "",
+ image: null,
+ // Only a single configured directory controls who can hold an email.
+ emailTrusted,
+ };
+}
+
+export async function buildOAuthProviders(
+ overrides?: Partial<Record<InstanceEnvKey, string>>
+): Promise<AuthOptions["providers"]> {
+ let resolved: Partial<Record<InstanceEnvKey, string>> = {};
+ if (overrides) {
+ resolved = overrides;
+ } else {
+ try {
+ resolved = await loadInstanceEnvOverrides();
+ } catch {
+ console.error("Instance environment overrides are unavailable");
+ }
+ }
+ const providers: AuthOptions["providers"] = [];
+ const googleId = configuredValue(resolved, "GOOGLE_CLIENT_ID", normalizeClientId);
+ const googleSecret = configuredValue(resolved, "GOOGLE_CLIENT_SECRET", normalizeSecret);
+ if (googleId && googleSecret) {
+ providers.push(GoogleProvider({ clientId: googleId, clientSecret: googleSecret }));
+ }
+
+ const githubId = configuredValue(resolved, "GITHUB_CLIENT_ID", normalizeClientId);
+ const githubSecret = configuredValue(resolved, "GITHUB_CLIENT_SECRET", normalizeSecret);
+ if (githubId && githubSecret) {
+ providers.push(GithubProvider({ clientId: githubId, clientSecret: githubSecret }));
+ }
+
+ const azureId = configuredValue(resolved, "AZURE_AD_CLIENT_ID", normalizeClientId);
+ const azureSecret = configuredValue(resolved, "AZURE_AD_CLIENT_SECRET", normalizeSecret);
+ const savedTenant = resolved.AZURE_AD_TENANT_ID?.trim();
+ const tenantRaw = savedTenant || (process.env.AZURE_AD_TENANT_ID || "").trim();
+ const tenant = tenantRaw ? normalizeAzureTenant(tenantRaw) : "common";
+ if (azureId && azureSecret && tenant) {
+ providers.push(
+ AzureADProvider({
+ clientId: azureId,
+ clientSecret: azureSecret,
+ tenantId: tenant,
+ profile(profile) {
+ return azureProfile(profile as Record<string, unknown>, !MULTI_TENANT_AZURE.has(tenant));
+ },
+ })
+ );
+ }
+
+ const oktaId = configuredValue(resolved, "OKTA_CLIENT_ID", normalizeClientId);
+ const oktaSecret = configuredValue(resolved, "OKTA_CLIENT_SECRET", normalizeSecret);
+ const issuer = configuredValue(resolved, "OKTA_ISSUER", normalizeOktaIssuer);
+ // The issuer is fetched server-side during sign-in, so it must resolve to a
+ // public address, not an internal service.
+ if (oktaId && oktaSecret && issuer && (await resolvesToPublicHost(new URL(issuer).hostname))) {
+ providers.push(
+ OktaProvider({
+ clientId: oktaId,
+ clientSecret: oktaSecret,
+ issuer,
+ })
+ );
+ }
+
+ return providers;
+}
diff --git a/src/client/src/lib/instance-admin/index.ts b/src/client/src/lib/instance-admin/index.ts
new file mode 100644
index 00000000..c9b990ae
--- /dev/null
+++ b/src/client/src/lib/instance-admin/index.ts
@@ -0,0 +1,18 @@
+import prisma from "@/lib/prisma";
+
+// The instance admin is the first account on the instance: the seeded user on a
+// fresh install, otherwise the first person to register. Users are never
+// deleted, so the earliest account is a stable owner for instance settings.
+export async function getInstanceAdminUserId(): Promise<string | null> {
+ const first = await prisma.user.findFirst({
+ orderBy: [{ createdAt: "asc" }, { id: "asc" }],
+ select: { id: true },
+ });
+ return first?.id ?? null;
+}
+
+export async function isInstanceAdminUser(userId?: string | null): Promise<boolean> {
+ if (!userId) return false;
+ const adminUserId = await getInstanceAdminUserId();
+ return adminUserId === userId;
+}
diff --git a/src/client/src/lib/instance-admin/route.ts b/src/client/src/lib/instance-admin/route.ts
new file mode 100644
index 00000000..a7841d10
--- /dev/null
+++ b/src/client/src/lib/instance-admin/route.ts
@@ -0,0 +1,22 @@
+import getMessage from "@/constants/messages";
+import { getCurrentUser } from "@/lib/session";
+// Alias import so enterprise can replace how admins are resolved.
+import { isInstanceAdminUser } from "@/lib/instance-admin";
+
+type RouteHandler = (request: any, context: any) => Promise<Response> | Response;
+
+// Middleware rejects non-admin tokens early, but the token claim can be stale,
+// so every instance admin route re-checks against the database.
+export function withInstanceAdmin<THandler extends RouteHandler>(handler: THandler): THandler {
+ return (async (request: Request, context: unknown) => {
+ const messages = getMessage();
+ const user = await getCurrentUser();
+ if (!user) {
+ return Response.json({ error: messages.UNAUTHORIZED_USER }, { status: 401 });
+ }
+ if (!(await isInstanceAdminUser(user.id))) {
+ return Response.json({ error: messages.INSTANCE_ADMIN_REQUIRED }, { status: 403 });
+ }
+ return handler(request, context);
+ }) as THandler;
+}
diff --git a/src/client/src/lib/instance-env/catalog.ts b/src/client/src/lib/instance-env/catalog.ts
new file mode 100644
index 00000000..f94645e1
--- /dev/null
+++ b/src/client/src/lib/instance-env/catalog.ts
@@ -0,0 +1,36 @@
+export const INSTANCE_ENV_GROUPS = ["google", "github", "microsoft", "okta"] as const;
+
+export type InstanceEnvGroup = (typeof INSTANCE_ENV_GROUPS)[number];
+
+export type InstanceEnvField = {
+ key: string;
+ group: InstanceEnvGroup;
+ secret: boolean;
+};
+
+export const INSTANCE_ENV_FIELDS = [
+ { key: "GOOGLE_CLIENT_ID", group: "google", secret: false },
+ { key: "GOOGLE_CLIENT_SECRET", group: "google", secret: true },
+ { key: "GITHUB_CLIENT_ID", group: "github", secret: false },
+ { key: "GITHUB_CLIENT_SECRET", group: "github", secret: true },
+ { key: "AZURE_AD_CLIENT_ID", group: "microsoft", secret: false },
+ { key: "AZURE_AD_CLIENT_SECRET", group: "microsoft", secret: true },
+ { key: "AZURE_AD_TENANT_ID", group: "microsoft", secret: false },
+ { key: "OKTA_CLIENT_ID", group: "okta", secret: false },
+ { key: "OKTA_CLIENT_SECRET", group: "okta", secret: true },
+ { key: "OKTA_ISSUER", group: "okta", secret: false },
+] as const satisfies readonly InstanceEnvField[];
+
+export type InstanceEnvKey = (typeof INSTANCE_ENV_FIELDS)[number]["key"];
+
+const FIELD_BY_KEY = new Map<string, (typeof INSTANCE_ENV_FIELDS)[number]>(
+ INSTANCE_ENV_FIELDS.map((field) => [field.key, field])
+);
+
+export function getInstanceEnvField(key: string) {
+ return FIELD_BY_KEY.get(key);
+}
+
+export function isInstanceEnvKey(key: string): key is InstanceEnvKey {
+ return FIELD_BY_KEY.has(key);
+}
diff --git a/src/client/src/lib/instance-env/describe.ts b/src/client/src/lib/instance-env/describe.ts
new file mode 100644
index 00000000..408ec6bd
--- /dev/null
+++ b/src/client/src/lib/instance-env/describe.ts
@@ -0,0 +1,33 @@
+import { INSTANCE_ENV_FIELDS, type InstanceEnvKey } from "./catalog";
+import { loadInstanceEnvOverrides } from "@/lib/instance-env/store";
+
+export type InstanceEnvSource = "instance" | "environment" | "unset";
+
+export type InstanceEnvVariable = {
+ key: InstanceEnvKey;
+ group: (typeof INSTANCE_ENV_FIELDS)[number]["group"];
+ secret: boolean;
+ source: InstanceEnvSource;
+ configured: boolean;
+ value: string | null;
+};
+
+export async function describeInstanceEnvironment(
+ overrides?: Partial<Record<InstanceEnvKey, string>>
+): Promise<InstanceEnvVariable[]> {
+ const resolved = overrides ?? (await loadInstanceEnvOverrides());
+ return INSTANCE_ENV_FIELDS.map((field) => {
+ const override = resolved[field.key]?.trim() || "";
+ const fromEnv = (process.env[field.key] || "").trim();
+ const source: InstanceEnvSource = override ? "instance" : fromEnv ? "environment" : "unset";
+ const effective = override || fromEnv;
+ return {
+ key: field.key,
+ group: field.group,
+ secret: field.secret,
+ source,
+ configured: Boolean(effective),
+ value: field.secret ? null : effective || null,
+ };
+ });
+}
diff --git a/src/client/src/lib/instance-env/http.ts b/src/client/src/lib/instance-env/http.ts
new file mode 100644
index 00000000..f817a02c
--- /dev/null
+++ b/src/client/src/lib/instance-env/http.ts
@@ -0,0 +1,14 @@
+import { disabledFeature } from "@/features/disabled-feature";
+import { withInstanceAdmin } from "@/lib/instance-admin/route";
+
+const FEATURE_ID = "enterprise.instance-admin";
+
+// Instance auth settings are an enterprise feature. The fallback still checks
+// the instance admin first, so other users never learn more than a 403.
+async function upgradeRequired(_request: Request, _context: unknown) {
+ return disabledFeature(FEATURE_ID).upgradeRequired();
+}
+
+export const GET = withInstanceAdmin(upgradeRequired);
+export const PATCH = withInstanceAdmin(upgradeRequired);
+export const VERIFY = withInstanceAdmin(upgradeRequired);
diff --git a/src/client/src/lib/instance-env/public-host.ts b/src/client/src/lib/instance-env/public-host.ts
new file mode 100644
index 00000000..b81ee806
--- /dev/null
+++ b/src/client/src/lib/instance-env/public-host.ts
@@ -0,0 +1,30 @@
+import { lookup } from "dns/promises";
+import { isPrivateIp } from "./values";
+
+const CACHE_TTL_MS = 5 * 60_000;
+const cache = new Map<string, { publicHost: boolean; expiresAt: number }>();
+
+/**
+ * Resolves a hostname and reports whether every address is public. Used before
+ * OpenLIT makes server-side requests to an admin-configured host such as the
+ * Okta issuer, so a public-looking name cannot point at an internal service.
+ */
+export async function resolvesToPublicHost(hostname: string): Promise<boolean> {
+ const host = hostname.toLowerCase().replace(/^\[|\]$/g, "");
+ const cached = cache.get(host);
+ if (cached && cached.expiresAt > Date.now()) return cached.publicHost;
+
+ let publicHost = false;
+ try {
+ const addresses = await lookup(host, { all: true });
+ publicHost = addresses.length > 0 && !addresses.some((entry) => isPrivateIp(entry.address));
+ } catch {
+ publicHost = false;
+ }
+ cache.set(host, { publicHost, expiresAt: Date.now() + CACHE_TTL_MS });
+ return publicHost;
+}
+
+export function clearPublicHostCache() {
+ cache.clear();
+}
diff --git a/src/client/src/lib/instance-env/store.ts b/src/client/src/lib/instance-env/store.ts
new file mode 100644
index 00000000..d19a2797
--- /dev/null
+++ b/src/client/src/lib/instance-env/store.ts
@@ -0,0 +1,7 @@
+import type { InstanceEnvKey } from "./catalog";
+
+// Open source reads deployment environment variables only. Enterprise replaces
+// this module and applies saved instance overrides before the environment.
+export async function loadInstanceEnvOverrides(): Promise<Partial<Record<InstanceEnvKey, string>>> {
+ return {};
+}
diff --git a/src/client/src/lib/instance-env/validate.ts b/src/client/src/lib/instance-env/validate.ts
new file mode 100644
index 00000000..3e336f53
--- /dev/null
+++ b/src/client/src/lib/instance-env/validate.ts
@@ -0,0 +1,72 @@
+import { getInstanceEnvField, isInstanceEnvKey, type InstanceEnvKey } from "./catalog";
+import { normalizeAzureTenant, normalizeClientId, normalizeOktaIssuer, normalizeSecret } from "./values";
+
+export type InstanceEnvParseError =
+ | "malformed"
+ | "unknown_key"
+ | "invalid_value"
+ | "invalid_issuer"
+ | "invalid_tenant";
+
+export type InstanceEnvChange =
+ | { key: InstanceEnvKey; action: "set"; value: string }
+ | { key: InstanceEnvKey; action: "clear" };
+
+export type InstanceEnvParseResult =
+ | { ok: true; changes: InstanceEnvChange[] }
+ | { ok: false; error: InstanceEnvParseError };
+
+function normalizeField(key: InstanceEnvKey, raw: string): { value: string } | { error: InstanceEnvParseError } {
+ if (key === "OKTA_ISSUER") {
+ const issuer = normalizeOktaIssuer(raw);
+ return issuer ? { value: issuer } : { error: "invalid_issuer" };
+ }
+ if (key === "AZURE_AD_TENANT_ID") {
+ const tenant = normalizeAzureTenant(raw);
+ return tenant ? { value: tenant } : { error: "invalid_tenant" };
+ }
+ const field = getInstanceEnvField(key);
+ const value = field?.secret ? normalizeSecret(raw) : normalizeClientId(raw);
+ return value ? { value } : { error: "invalid_value" };
+}
+
+export function parseInstanceEnvUpdates(body: unknown): InstanceEnvParseResult {
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
+ return { ok: false, error: "malformed" };
+ }
+ const updates = (body as { updates?: unknown }).updates;
+ if (!Array.isArray(updates) || updates.length > 20) {
+ return { ok: false, error: "malformed" };
+ }
+
+ const changes = new Map<InstanceEnvKey, InstanceEnvChange>();
+ for (const item of updates) {
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
+ return { ok: false, error: "malformed" };
+ }
+ const record = item as { key?: unknown; value?: unknown; clear?: unknown };
+ if (typeof record.key !== "string" || !isInstanceEnvKey(record.key)) {
+ return { ok: false, error: record.key === undefined ? "malformed" : "unknown_key" };
+ }
+ if (record.clear === true) {
+ changes.set(record.key, { key: record.key, action: "clear" });
+ continue;
+ }
+ if (record.value === undefined) return { ok: false, error: "malformed" };
+ if (typeof record.value !== "string") return { ok: false, error: "malformed" };
+
+ const field = getInstanceEnvField(record.key);
+ if (field?.secret && !record.value.trim()) continue;
+
+ if (!record.value.trim()) {
+ changes.set(record.key, { key: record.key, action: "clear" });
+ continue;
+ }
+
+ const normalized = normalizeField(record.key, record.value);
+ if ("error" in normalized) return { ok: false, error: normalized.error };
+ changes.set(record.key, { key: record.key, action: "set", value: normalized.value });
+ }
+
+ return { ok: true, changes: Array.from(changes.values()) };
+}
diff --git a/src/client/src/lib/instance-env/values.ts b/src/client/src/lib/instance-env/values.ts
new file mode 100644
index 00000000..75100810
--- /dev/null
+++ b/src/client/src/lib/instance-env/values.ts
@@ -0,0 +1,88 @@
+import net from "net";
+
+const BLOCKED_HOSTS = new Set([
+ "localhost",
+ "localhost.localdomain",
+ "metadata.google.internal",
+ "metadata.goog",
+ "metadata.azure.com",
+ "instance-data",
+ "169.254.169.254",
+]);
+
+export function isPrivateIp(ip: string) {
+ const version = net.isIP(ip);
+ if (version === 4) {
+ const parts = ip.split(".").map(Number);
+ if (parts.length !== 4 || parts.some((part) => Number.isNaN(part))) return true;
+ if (parts[0] === 10 || parts[0] === 127 || parts[0] === 0) return true;
+ if (parts[0] === 169 && parts[1] === 254) return true;
+ if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
+ if (parts[0] === 192 && parts[1] === 168) return true;
+ if (parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127) return true;
+ return false;
+ }
+ if (version === 6) {
+ const lower = ip.toLowerCase();
+ // IPv4-mapped addresses (::ffff:10.0.0.1) carry an IPv4 address.
+ const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/.exec(lower);
+ if (mapped) return isPrivateIp(mapped[1]);
+ if (lower === "::1" || lower === "::") return true;
+ if (lower.startsWith("fe80:") || lower.startsWith("fc") || lower.startsWith("fd")) return true;
+ return false;
+ }
+ return false;
+}
+
+export function normalizeClientId(raw: string): string | null {
+ const value = raw.trim();
+ if (!value || value.length > 512) return null;
+ if (!/^[A-Za-z0-9._~@+:/=-]+$/.test(value)) return null;
+ return value;
+}
+
+export function normalizeSecret(raw: string): string | null {
+ const value = raw.trim();
+ if (!value || value.length > 2048) return null;
+ if (/[\u0000-\u001F\u007F]/.test(value)) return null;
+ return value;
+}
+
+export function normalizeAzureTenant(raw: string): string | null {
+ const value = raw.trim();
+ if (!value || value.length > 253) return null;
+ if (/^(common|organizations|consumers)$/i.test(value)) return value.toLowerCase();
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) {
+ return value.toLowerCase();
+ }
+ const host = value.toLowerCase().replace(/\.$/, "");
+ if (!/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/.test(host)) return null;
+ if (!host.includes(".") || host.includes("..")) return null;
+ if (BLOCKED_HOSTS.has(host) || host.endsWith(".local") || host.endsWith(".internal")) return null;
+ return host;
+}
+
+export function normalizeOktaIssuer(raw: string): string | null {
+ const trimmed = raw.trim();
+ if (!trimmed || trimmed.length > 256) return null;
+ let url: URL;
+ try {
+ url = new URL(trimmed);
+ } catch {
+ return null;
+ }
+ if (url.protocol !== "https:") return null;
+ if (url.username || url.password || url.search || url.hash) return null;
+ // URL keeps IPv6 hosts bracketed ("[::1]"); strip them so the IP checks apply.
+ const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
+ if (!host || net.isIP(host)) return null;
+ if (BLOCKED_HOSTS.has(host) || host.endsWith(".local") || host.endsWith(".internal") || host.endsWith(".localhost")) {
+ return null;
+ }
+ if (isPrivateIp(host)) return null;
+ let path = url.pathname.replace(/\/+$/, "");
+ const wellKnown = "/.well-known/openid-configuration";
+ if (path.endsWith(wellKnown)) path = path.slice(0, -wellKnown.length);
+ if (path.includes("..")) return null;
+ return `${url.origin}${path}`;
+}
diff --git a/src/client/src/middleware.ts b/src/client/src/middleware.ts
index faa98683..5950e951 100644
--- a/src/client/src/middleware.ts
+++ b/src/client/src/middleware.ts
@@ -40,6 +40,8 @@ export const config = {
"/vault",
"/vault/:path*",
"/settings/:path*",
+ "/admin",
+ "/admin/:path*",
"/telemetry-enabled",
"/home",
"/dashboards/:path*",
diff --git a/src/client/src/middleware/check-auth.ts b/src/client/src/middleware/check-auth.ts
index f215bc67..9bd828f3 100644
--- a/src/client/src/middleware/check-auth.ts
+++ b/src/client/src/middleware/check-auth.ts
@@ -17,6 +17,8 @@ import {
ONBOARDING_WHITELIST_ROUTES,
ONBOARDING_WHITELIST_ROUTE_PREFIXES,
ONBOARDING_WHITELIST_API_ROUTES,
+ INSTANCE_ADMIN_ROUTE_PREFIX,
+ INSTANCE_ADMIN_API_ROUTE_PREFIX,
} from "@/constants/route";
import { isValidCronJobRequest } from "@/helpers/server/cron-auth";
import { isApiKeyPathAllowed } from "@/lib/platform/api-key-access/scopes";
@@ -50,11 +52,16 @@ const RATE_LIMITED_API_PREFIXES = [
"/api/agents",
"/api/alerts",
"/api/vault",
+ "/api/admin",
"/api/context",
"/api/manage-dashboard",
];
let nextRateLimitCleanupAt = 0;
+function isWithinPrefix(pathname: string, prefix: string) {
+ return pathname === prefix || pathname.startsWith(`${prefix}/`);
+}
+
function shouldRateLimitApi(pathname: string) {
return RATE_LIMITED_API_PREFIXES.some((prefix) => pathname.startsWith(prefix));
}
@@ -213,6 +220,8 @@ export default function checkAuth(next: NextMiddleware) {
pathname.startsWith("/login") || pathname.startsWith("/register");
const isApiPage = pathname.startsWith("/api");
const isRateLimitedApi = shouldRateLimitApi(pathname);
+ const isInstanceAdminPage = isWithinPrefix(pathname, INSTANCE_ADMIN_ROUTE_PREFIX);
+ const isInstanceAdminApi = isWithinPrefix(pathname, INSTANCE_ADMIN_API_ROUTE_PREFIX);
const method = request.method.toUpperCase();
const isOnboardingWhitelistedPage = ONBOARDING_WHITELIST_ROUTES.includes(
pathname
@@ -268,6 +277,20 @@ export default function checkAuth(next: NextMiddleware) {
);
}
+ // Instance admin APIs need a session whose user is the instance
+ // admin. Route handlers repeat the check against the database.
+ if (isInstanceAdminApi) {
+ if (!isAuth) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+ if (token.isInstanceAdmin !== true) {
+ return NextResponse.json(
+ { error: getMessage().INSTANCE_ADMIN_REQUIRED },
+ { status: 403 }
+ );
+ }
+ }
+
if (isEngineRoute) {
// Edge middleware cannot use Node crypto; the route handler
// does the constant-time secret check.
@@ -330,6 +353,12 @@ export default function checkAuth(next: NextMiddleware) {
);
}
+ if (isInstanceAdminPage && token.isInstanceAdmin !== true) {
+ return NextResponse.redirect(
+ new URL(DEFAULT_LOGGED_IN_ROUTE, request.url)
+ );
+ }
+
return continueWithoutClientTenant();
} catch (error) {
// If there's an error getting the token (e.g., invalid/corrupted token),
diff --git a/src/dev-docker-compose.yml b/src/dev-docker-compose.yml
index 48068fec..6465cebf 100644
--- a/src/dev-docker-compose.yml
+++ b/src/dev-docker-compose.yml
@@ -81,6 +81,12 @@ services:
GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET:-}
GITHUB_CLIENT_ID: ${GITHUB_CLIENT_ID:-}
GITHUB_CLIENT_SECRET: ${GITHUB_CLIENT_SECRET:-}
+ AZURE_AD_CLIENT_ID: ${AZURE_AD_CLIENT_ID:-}
+ AZURE_AD_CLIENT_SECRET: ${AZURE_AD_CLIENT_SECRET:-}
+ AZURE_AD_TENANT_ID: ${AZURE_AD_TENANT_ID:-}
+ OKTA_CLIENT_ID: ${OKTA_CLIENT_ID:-}
+ OKTA_CLIENT_SECRET: ${OKTA_CLIENT_SECRET:-}
+ OKTA_ISSUER: ${OKTA_ISSUER:-}
env_file:
- path: .env