Compare commits

...

3 Commits

Author SHA1 Message Date
swapnil-signoz
346e6cee67 test(fileauditor): cover the audit file write path end to end 2026-11-16 18:30:11 +05:30
hardik-signoz
ce78251920 fix(onboarding): skip onboarding flow for admin@signoz.cloud (#13600)
#### Description

- Stop redirecting `admin@signoz.cloud` to `/onboarding`. The first-user
check excluded that email from the user count but not from the redirect,
so support was locked out of every page on a new deployment until the
customer finished the questionnaire.
- Move the email to a `SIGNOZ_ADMIN_EMAIL` constant, shared by the user
filter and the redirect check.

#### Issues closed by this PR

Closes SigNoz/keystone-pod#217
2026-11-16 09:33:49 +00:00
Ashwin Bhatkal
879b6e4e69 ci(e2e): start e2e on the safe-to-e2e label and run it in the merge queue (#13595)
#### Description

- Adding the `safe-to-e2e` label now starts e2e right away. Before,
`e2eci` ignored label events, so the label only took effect on the next
push or reopen.
- Other labels get their own concurrency group and report as
`ignored-label`, so they never cancel a running e2e or hide its `e2e`
result. They still add a short run of skipped jobs to the checks list.
- The merge queue now runs the full test suite and reports a real `e2e`
result, instead of passing without running anything. Full runs take 17
to 27 minutes, inside the 60-minute queue timeout.
- `fmtlint` is skipped in the merge queue. It only checks `tests/e2e/`,
which each PR's own run already covers.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/736
2026-11-16 08:25:19 +00:00
12 changed files with 352 additions and 12 deletions

View File

@@ -2,44 +2,50 @@ name: e2eci
on:
pull_request:
types:
- opened
- synchronize
- reopened
- labeled
merge_group:
types:
- checks_requested
# Labels other than safe-to-e2e get a group of their own, so they never cancel a running e2e.
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}${{ github.event.action == 'labeled' && github.event.label.name != 'safe-to-e2e' && format('-{0}', github.run_id) || '' }}
cancel-in-progress: true
jobs:
changes:
if: github.event.action != 'labeled' || github.event.label.name == 'safe-to-e2e'
runs-on: ubuntu-latest
outputs:
e2e: ${{ steps.changes.outputs.e2e }}
steps:
- name: merge-queue-pass
if: github.event_name == 'merge_group'
run: echo "::notice::Merge queue run. E2E already gated the PR, so the required e2e check auto-passes."
- name: changes
id: changes
if: github.event_name == 'pull_request'
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
FORCE: ${{ contains(github.event.pull_request.labels.*.name, 'safe-to-e2e') }}
FORCE: ${{ github.event_name == 'merge_group' || contains(github.event.pull_request.labels.*.name, 'safe-to-e2e') }}
run: |
if [ "$FORCE" = "true" ]; then
echo "e2e=true" >> "$GITHUB_OUTPUT"
exit 0
fi
CHANGED_FILES=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER/files" --paginate --jq '.[].filename | select((startswith("tests/integration/") or startswith("frontend/src/api/generated/")) | not)')
PATTERN='^(frontend/|tests/|\.github/workflows/e2eci\.yaml$|cmd/enterprise/Dockerfile\.with-web\.integration$)'
if [ "$FORCE" = "true" ]; then
echo "e2e=true" >> "$GITHUB_OUTPUT"
elif printf '%s\n' "$CHANGED_FILES" | grep -qE "$PATTERN"; then
if printf '%s\n' "$CHANGED_FILES" | grep -qE "$PATTERN"; then
echo "e2e=true" >> "$GITHUB_OUTPUT"
else
echo "e2e=false" >> "$GITHUB_OUTPUT"
fi
fmtlint:
needs: changes
if: needs.changes.outputs.e2e == 'true'
if: github.event_name != 'merge_group' && needs.changes.outputs.e2e == 'true'
runs-on: ubuntu-latest
steps:
- name: checkout
@@ -180,6 +186,8 @@ jobs:
retention-days: 5
# Required status check. Fails when e2e was needed but did not pass.
e2e:
# Runs for other labels must not report as e2e, or their pass would hide the real result.
name: ${{ github.event.action == 'labeled' && github.event.label.name != 'safe-to-e2e' && 'ignored-label' || 'e2e' }}
if: always()
needs: [changes, fmtlint, test]
runs-on: ubuntu-latest

View File

@@ -45,6 +45,7 @@ jobs:
- callbackauthn
- cloudintegrations
- dashboard
- fileauditor
- ingestionkeys
- inframonitoring
- llmpricingrules

View File

@@ -13,6 +13,7 @@ import { useAppContext } from 'providers/App/App';
import { LicensePlatform, LicenseState } from 'types/api/licensesV3/getActive';
import { OrgPreference } from 'types/api/preferences/preference';
import { USER_ROLES } from 'types/roles';
import { isSignozAdminEmail } from 'utils/app';
import {
routePermission,
routeWithInitialAuthZSupport,
@@ -75,7 +76,7 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
const users = usersData?.data || [];
const remainingUsers = (Array.isArray(users) ? users : []).filter(
(user) => user.email !== 'admin@signoz.cloud',
(u) => !isSignozAdminEmail(u.email),
);
return remainingUsers.length === 1;
@@ -203,6 +204,7 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
const isFirstUser = checkFirstTimeUser();
if (
isFirstUser &&
!isSignozAdminEmail(user.email) &&
!isOnboardingComplete &&
!ROUTES_NOT_TO_BE_OVERRIDEN.includes(pathname) &&
pathname !== ROUTES.ONBOARDING

View File

@@ -2,6 +2,7 @@ import { ReactElement } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { MemoryRouter, Route, Switch, useLocation } from 'react-router-dom';
import { act, render, screen, waitFor } from '@testing-library/react';
import { SIGNOZ_ADMIN_EMAIL } from 'constants/app';
import { LOCALSTORAGE } from 'constants/localStorage';
import { ORG_PREFERENCES } from 'constants/orgPreferences';
import ROUTES from 'constants/routes';
@@ -1089,6 +1090,33 @@ describe('PrivateRoute', () => {
await assertRedirectsTo(ROUTES.ONBOARDING);
});
it('should not redirect the signoz admin to onboarding while the first user has not completed it', async () => {
mockUsersData = [
{ email: 'test@example.com' },
{ email: SIGNOZ_ADMIN_EMAIL },
];
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingOrgPreferences: false,
orgPreferences: createMockOrgPreferences(false),
user: createMockUser({
role: USER_ROLES.ADMIN as ROLES,
email: SIGNOZ_ADMIN_EMAIL,
}),
},
isCloudUser: true,
});
await act(async () => {
await Promise.resolve();
});
assertStaysOnRoute(ROUTES.HOME);
});
it('should not redirect to onboarding when org preferences are still fetching', () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,

View File

@@ -15,3 +15,5 @@ export const DASHBOARD_TIME_IN_DURATION = 'refreshInterval';
export const DEFAULT_ENTITY_VERSION = 'v3';
export const ENTITY_VERSION_V4 = 'v4';
export const ENTITY_VERSION_V5 = 'v5';
export const SIGNOZ_ADMIN_EMAIL = 'admin@signoz.cloud';

View File

@@ -1,4 +1,6 @@
import { buildAbsolutePath } from '../app';
import { SIGNOZ_ADMIN_EMAIL } from 'constants/app';
import { buildAbsolutePath, isSignozAdminEmail } from '../app';
// buildAbsolutePath reads getCurrentLocation().pathname (basename-relative) rather than
// window.location.pathname, so we mock lib/router/navigation instead of utils/getLocation.
@@ -122,3 +124,13 @@ describe('buildAbsolutePath', () => {
});
});
});
describe('isSignozAdminEmail', () => {
it('matches the SigNoz admin email', () => {
expect(isSignozAdminEmail(SIGNOZ_ADMIN_EMAIL)).toBe(true);
});
it.each(['jon@winterfell.dev', '', undefined])('rejects %p', (email) => {
expect(isSignozAdminEmail(email)).toBe(false);
});
});

View File

@@ -1,4 +1,5 @@
import getLocalStorage from 'api/browser/localstorage/get';
import { SIGNOZ_ADMIN_EMAIL } from 'constants/app';
import { FeatureKeys } from 'constants/features';
import { SKIP_ONBOARDING } from 'constants/onboarding';
import dayjs from 'dayjs';
@@ -16,6 +17,9 @@ export function extractDomain(email: string): string {
return emailParts[1];
}
export const isSignozAdminEmail = (email?: string): boolean =>
email === SIGNOZ_ADMIN_EMAIL;
const stripVersionPrefix = (version: string): string =>
version?.replace(/^v/i, '') ?? '';

51
tests/fixtures/fileauditor.py vendored Normal file
View File

@@ -0,0 +1,51 @@
import json
import time
import docker
from fixtures import types
AUDIT_FILE_PATH = "/tmp/audit.log"
def list_audit_events(signoz: types.SigNoz) -> list[dict]:
"""Each line of the audit file is one OTLP JSON batch of events; this flattens all batches into events."""
exit_code, output = docker.from_env().containers.get(signoz.self.id).exec_run(["cat", AUDIT_FILE_PATH])
assert exit_code == 0, output.decode()
events = []
for line in output.decode().splitlines():
for resource_logs in json.loads(line)["resourceLogs"]:
resource = _attributes(resource_logs["resource"]["attributes"])
for scope_logs in resource_logs["scopeLogs"]:
for log_record in scope_logs["logRecords"]:
events.append(
{
"event_name": log_record["eventName"],
"severity_text": log_record["severityText"],
"body": log_record["body"]["stringValue"],
"scope_name": scope_logs["scope"]["name"],
"resource": resource,
"attributes": _attributes(log_record["attributes"]),
}
)
return events
def wait_for_audit_event(signoz: types.SigNoz, event_name: str, resource_id: str, target_id: str | None = None, wait_seconds: int = 10) -> dict:
deadline = time.time() + wait_seconds
events = []
while time.time() < deadline:
events = list_audit_events(signoz)
matched = [event for event in events if event["event_name"] == event_name and event["resource"].get("signoz.resource.id") == resource_id and (target_id is None or event["attributes"].get("signoz.resource.target.id") == target_id)]
if len(matched) > 0:
return matched[0]
time.sleep(0.5)
raise AssertionError(f"No {event_name} audit event for resource {resource_id} (target {target_id}) within {wait_seconds}s, events: {events}")
def _attributes(otlp_attributes: list[dict]) -> dict:
# OTLP JSON encodes int64 values as decimal strings.
return {attribute["key"]: int(attribute["value"]["intValue"]) if "intValue" in attribute["value"] else attribute["value"]["stringValue"] for attribute in otlp_attributes}

View File

@@ -0,0 +1,151 @@
import uuid
from collections.abc import Callable
from http import HTTPStatus
import requests
from fixtures import types
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD, find_user_by_email
from fixtures.fileauditor import wait_for_audit_event
from fixtures.savedview import SAVED_VIEW_BASE, create_saved_view
from fixtures.serviceaccount import SERVICE_ACCOUNT_BASE, create_service_account, create_service_account_with_key, delete_service_account, get_first_key_id
def test_create_saved_view_writes_create_event(
signoz: types.SigNoz,
apply_license: types.Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
admin = find_user_by_email(signoz, token, USER_ADMIN_EMAIL)
view_id = create_saved_view(signoz, token, f"fileauditor-{uuid.uuid4().hex[:8]}")
event = wait_for_audit_event(signoz, "signoz.audit.create", view_id)
assert event["severity_text"] == "INFO"
assert event["scope_name"] == "signoz.audit"
assert event["resource"]["service.name"] == "signoz"
assert event["resource"]["signoz.resource.kind"] == "saved-view"
assert event["attributes"]["signoz.audit.verb"] == "create"
assert event["attributes"]["signoz.audit.outcome"] == "success"
assert event["attributes"]["signoz.principal.id"] == admin["id"]
assert event["attributes"]["signoz.principal.email"] == USER_ADMIN_EMAIL
assert event["attributes"]["signoz.organization.id"] == admin["orgId"]
assert event["attributes"]["http.request.method"] == "POST"
assert event["attributes"]["http.route"] == "/api/v2/saved_views"
assert event["attributes"]["http.response.status_code"] == HTTPStatus.CREATED
def test_update_service_account_writes_update_event(
signoz: types.SigNoz,
apply_license: types.Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
service_account_id = create_service_account(signoz, token, f"fileauditor-{uuid.uuid4().hex[:8]}")
response = requests.put(
signoz.self.host_configs["8080"].get(f"{SERVICE_ACCOUNT_BASE}/{service_account_id}"),
json={"name": f"fileauditor-{uuid.uuid4().hex[:8]}"},
headers={"Authorization": f"Bearer {token}"},
timeout=5,
)
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
event = wait_for_audit_event(signoz, "signoz.audit.update", service_account_id)
assert event["resource"]["signoz.resource.kind"] == "serviceaccount"
assert event["attributes"]["signoz.audit.verb"] == "update"
assert event["attributes"]["signoz.audit.outcome"] == "success"
assert event["attributes"]["http.route"] == "/api/v1/service_accounts/{id}"
assert event["attributes"]["http.response.status_code"] == HTTPStatus.NO_CONTENT
def test_delete_service_account_writes_delete_event(
signoz: types.SigNoz,
apply_license: types.Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
service_account_id = create_service_account(signoz, token, f"fileauditor-{uuid.uuid4().hex[:8]}")
delete_service_account(signoz, token, service_account_id)
event = wait_for_audit_event(signoz, "signoz.audit.delete", service_account_id)
assert event["resource"]["signoz.resource.kind"] == "serviceaccount"
assert event["attributes"]["signoz.audit.verb"] == "delete"
assert event["attributes"]["signoz.audit.outcome"] == "success"
assert event["attributes"]["http.route"] == "/api/v1/service_accounts/{id}"
assert event["attributes"]["http.response.status_code"] == HTTPStatus.NO_CONTENT
def test_create_service_account_key_writes_attach_event(
signoz: types.SigNoz,
apply_license: types.Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
service_account_id = create_service_account(signoz, token, f"fileauditor-{uuid.uuid4().hex[:8]}")
response = requests.post(
signoz.self.host_configs["8080"].get(f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/keys"),
json={"name": "fileauditor", "expiresAt": 0},
headers={"Authorization": f"Bearer {token}"},
timeout=5,
)
assert response.status_code == HTTPStatus.CREATED, response.text
key_id = response.json()["data"]["id"]
event = wait_for_audit_event(signoz, "signoz.audit.attach", service_account_id, target_id=key_id)
assert event["resource"]["signoz.resource.kind"] == "serviceaccount"
assert event["attributes"]["signoz.resource.target.kind"] == "factor-api-key"
assert event["attributes"]["signoz.audit.verb"] == "attach"
assert event["attributes"]["signoz.audit.outcome"] == "success"
assert event["attributes"]["http.route"] == "/api/v1/service_accounts/{id}/keys"
assert event["attributes"]["http.response.status_code"] == HTTPStatus.CREATED
def test_revoke_service_account_key_writes_detach_event(
signoz: types.SigNoz,
apply_license: types.Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
service_account_id, _ = create_service_account_with_key(signoz, token, f"fileauditor-{uuid.uuid4().hex[:8]}")
key_id = get_first_key_id(signoz, token, service_account_id)
response = requests.delete(
signoz.self.host_configs["8080"].get(f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/keys/{key_id}"),
headers={"Authorization": f"Bearer {token}"},
timeout=5,
)
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
event = wait_for_audit_event(signoz, "signoz.audit.detach", service_account_id, target_id=key_id)
assert event["resource"]["signoz.resource.kind"] == "serviceaccount"
assert event["attributes"]["signoz.resource.target.kind"] == "factor-api-key"
assert event["attributes"]["signoz.audit.verb"] == "detach"
assert event["attributes"]["signoz.audit.outcome"] == "success"
assert event["attributes"]["http.route"] == "/api/v1/service_accounts/{id}/keys/{fid}"
assert event["attributes"]["http.response.status_code"] == HTTPStatus.NO_CONTENT
def test_delete_missing_saved_view_writes_failure_event(
signoz: types.SigNoz,
apply_license: types.Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
missing_view_id = str(uuid.uuid4())
response = requests.delete(
signoz.self.host_configs["8080"].get(f"{SAVED_VIEW_BASE}/{missing_view_id}"),
headers={"Authorization": f"Bearer {token}"},
timeout=5,
)
assert response.status_code == HTTPStatus.NOT_FOUND, response.text
event = wait_for_audit_event(signoz, "signoz.audit.delete", missing_view_id)
assert event["severity_text"] == "ERROR"
assert event["attributes"]["signoz.audit.outcome"] == "failure"
assert event["attributes"]["exception.type"] == "not-found"
assert event["attributes"]["http.response.status_code"] == HTTPStatus.NOT_FOUND

View File

@@ -0,0 +1,49 @@
import uuid
from collections.abc import Callable
from sqlalchemy import sql
from fixtures import types
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
from fixtures.fileauditor import list_audit_events, wait_for_audit_event
from fixtures.savedview import create_saved_view
def test_unlicensed_create_writes_no_event(
signoz: types.SigNoz,
apply_license: types.Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
with signoz.sqlstore.conn.begin() as conn:
licenses = conn.execute(sql.text("SELECT id, created_at, updated_at, key, data, last_validated_at, org_id FROM license")).mappings().all()
assert len(licenses) > 0
conn.execute(sql.text("DELETE FROM license"))
try:
unlicensed_view_id = create_saved_view(signoz, token, f"fileauditor-{uuid.uuid4().hex[:8]}")
finally:
with signoz.sqlstore.conn.begin() as conn:
conn.execute(
sql.text("INSERT INTO license (id, created_at, updated_at, key, data, last_validated_at, org_id) VALUES (:id, :created_at, :updated_at, :key, :data, :last_validated_at, :org_id)"),
[dict(row) for row in licenses],
)
marker_view_id = create_saved_view(signoz, token, f"fileauditor-{uuid.uuid4().hex[:8]}")
wait_for_audit_event(signoz, "signoz.audit.create", marker_view_id)
assert all(event["resource"].get("signoz.resource.id") != unlicensed_view_id for event in list_audit_events(signoz))
def test_login_writes_no_event(
signoz: types.SigNoz,
apply_license: types.Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
marker_view_id = create_saved_view(signoz, token, f"fileauditor-{uuid.uuid4().hex[:8]}")
wait_for_audit_event(signoz, "signoz.audit.create", marker_view_id)
assert all(event["attributes"].get("http.route") != "/api/v2/sessions/email_password" for event in list_audit_events(signoz))

View File

@@ -0,0 +1,32 @@
import pytest
from testcontainers.core.container import Network
from fixtures import types
from fixtures.fileauditor import AUDIT_FILE_PATH
from fixtures.signoz import create_signoz
@pytest.fixture(name="signoz", scope="package")
def signoz_fileauditor(
network: Network,
zeus: types.TestContainerDocker,
gateway: types.TestContainerDocker,
sqlstore: types.TestContainerSQL,
clickhouse: types.TestContainerClickhouse,
request: pytest.FixtureRequest,
pytestconfig: pytest.Config,
) -> types.SigNoz:
return create_signoz(
network=network,
zeus=zeus,
gateway=gateway,
sqlstore=sqlstore,
clickhouse=clickhouse,
request=request,
pytestconfig=pytestconfig,
cache_key="signoz-fileauditor",
env_overrides={
"SIGNOZ_AUDITOR_PROVIDER": "file",
"SIGNOZ_AUDITOR_FILE_PATH": AUDIT_FILE_PATH,
},
)