[Auth] Couvrir la première connexion après création par rôle (#329)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Failing after 21m23s
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Failing after 2s
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Failing after 21m23s
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Failing after 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
This commit was merged in pull request #329.
This commit is contained in:
1 parent
7c0c8ecf46
commit
aef04552a8
3 files changed
+194
No files matched your search
@@ -28,6 +28,8 @@ Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../git
|
||||
- For cookie session validation changes, prove a freshly issued cookie succeeds before account mutation and fails afterward for lockout, role/security-stamp, email, and password changes. Treat GlitchTip blocking warnings as hypotheses: inspect the full async stack and do not claim a synchronous block solely from the warning title.
|
||||
- For behavior changes, update FR/EN resources and UI/API contracts, add focused tests, update the Gitea issue, and run the disposable Compose acceptance recipe with unique credentials, ports, volumes, project name, and network.
|
||||
- Acceptance must exercise bootstrap through the setup UI, user lifecycle and role editing through `/users`, permission editing through `/admin/claims`, and verify the resulting JWT/API allow and deny decisions. Check that stale sessions fail after a role/permission change and that the last usable Admin cannot be demoted, deleted, or locked.
|
||||
- For account-creation password regressions, cover the real `/users` dialog for Viewer and Supervisor with the role selected both before and after password entry. Confirm the new account's email through the admin row action, then authenticate through `/api/auth/login` using the exact synthetic password entered in the form; assert only the status/token presence and never log the password. Keep this as a Playwright E2E test under the `E2E` collection.
|
||||
- The account-creation disposable Compose acceptance must use a unique project, generated PostgreSQL/JWT credentials, a free loopback port, and a project-specific Central image tag. Build from the checkout, wait for `/healthz`, then run the create/confirm/login HTTP API path against that stack; the separate Playwright E2E test covers UI role selection. Teardown only that Compose project and verify its containers, volumes, and network are gone; remove and verify absence of the exact Central tag while retaining PostgreSQL and other shared base images.
|
||||
- Record a project-unique tag for each source-built Central acceptance image and install an EXIT cleanup trap before build/start. After scoped Compose teardown, verify zero containers/volumes/networks and remove/verify absence of each exact local tag even on failure. Keep shared upstream base images, preserve test exit status, report cleanup failures, and avoid `--rmi all` or broad image-prune commands.
|
||||
|
||||
Useful official references: [ASP.NET Core Identity configuration](https://learn.microsoft.com/aspnet/core/security/authentication/identity-configuration), [Two-factor authentication](https://learn.microsoft.com/aspnet/core/security/authentication/identity-enable-qrcodes), and [Data Protection](https://learn.microsoft.com/aspnet/core/security/data-protection/introduction).
|
||||
Executable
+134
@@ -0,0 +1,134 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
suffix="$(date -u +%Y%m%d%H%M%S)-$(od -An -N5 -tx1 /dev/urandom | tr -d ' \\n')"
|
||||
project="heimdall-auth-create-${suffix}"
|
||||
central_image="heimdall:${project}-central"
|
||||
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
|
||||
env_file="$temp_dir/acceptance.env"
|
||||
override_file="$temp_dir/compose.override.yml"
|
||||
compose_file="$repo_root/docker/docker-compose.yml"
|
||||
local_image_tags=("$central_image")
|
||||
compose_port=$(python3 - <<'PY'
|
||||
import socket
|
||||
with socket.socket() as sock:
|
||||
sock.bind(('127.0.0.1', 0))
|
||||
print(sock.getsockname()[1])
|
||||
PY
|
||||
)
|
||||
web_port=$(python3 - <<'PY'
|
||||
import socket
|
||||
with socket.socket() as sock:
|
||||
sock.bind(('127.0.0.1', 0))
|
||||
print(sock.getsockname()[1])
|
||||
PY
|
||||
)
|
||||
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - EXIT
|
||||
cleanup_failed=0
|
||||
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$override_file" \
|
||||
down --volumes --remove-orphans || cleanup_failed=1
|
||||
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
|
||||
if [[ -n "$containers" || -n "$volumes" || -n "$networks" ]]; then
|
||||
printf 'Project resources remain: containers=%s volumes=%s networks=%s\n' \
|
||||
"${containers:-<none>}" "${volumes:-<none>}" "${networks:-<none>}" >&2
|
||||
cleanup_failed=1
|
||||
else
|
||||
printf 'Verified no project containers, volumes, or networks remain: %s\n' "$project"
|
||||
fi
|
||||
for tag in "${local_image_tags[@]}"; do
|
||||
docker image rm "$tag" >/dev/null 2>&1 || true
|
||||
if docker image inspect "$tag" >/dev/null 2>&1; then
|
||||
printf 'Recipe image remains: %s\n' "$tag" >&2
|
||||
cleanup_failed=1
|
||||
else
|
||||
printf 'Verified recipe image absent: %s\n' "$tag"
|
||||
fi
|
||||
done
|
||||
rm -f -- "$env_file" "$override_file" || cleanup_failed=1
|
||||
rmdir -- "$temp_dir" || cleanup_failed=1
|
||||
if (( cleanup_failed )); then status=1; fi
|
||||
exit "$status"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
pg_password=$(python3 - <<'PY'
|
||||
import secrets, string
|
||||
alphabet=string.ascii_letters+string.digits
|
||||
print(''.join(secrets.choice(alphabet) for _ in range(40)))
|
||||
PY
|
||||
)
|
||||
jwt_key=$(od -An -N48 -tx1 /dev/urandom | tr -d ' \\n')
|
||||
refresh_key=$(od -An -N48 -tx1 /dev/urandom | tr -d ' \\n')
|
||||
admin_password=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \\n')
|
||||
admin_password="${admin_password}Aa1!"
|
||||
cat >"$env_file" <<EOF
|
||||
ACCEPTANCE_PROJECT=$project
|
||||
POSTGRES_DB=heimdall_acceptance
|
||||
POSTGRES_USER=heimdall_acceptance
|
||||
POSTGRES_PASSWORD=$pg_password
|
||||
POSTGRES_PORT=$compose_port
|
||||
WEB_PORT=$web_port
|
||||
DATABASE_URL="Host=postgresql;Port=5432;Database=heimdall_acceptance;Username=heimdall_acceptance;Password=$pg_password;Timeout=60;Command Timeout=300"
|
||||
JWT__KEY=$jwt_key
|
||||
JWT__REFRESHKEY=$refresh_key
|
||||
JWT__ISSUER=heimdall-acceptance
|
||||
JWT__AUDIENCE=heimdall-acceptance
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
HEIMDALL_NETWORK_NAME=${project}-net
|
||||
EOF
|
||||
cat >"$override_file" <<EOF
|
||||
services:
|
||||
heimdall:
|
||||
image: $central_image
|
||||
environment:
|
||||
Database__MigrateOnStartup: "true"
|
||||
EOF
|
||||
|
||||
printf 'Disposable project: %s\nCentral image: %s\n' "$project" "$central_image"
|
||||
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$override_file" up -d --build
|
||||
|
||||
base_url="http://127.0.0.1:$web_port"
|
||||
deadline=$((SECONDS + 300))
|
||||
until curl -fsS "$base_url/healthz" >/dev/null 2>&1; do
|
||||
if (( SECONDS >= deadline )); then echo 'Central health check timed out' >&2; exit 1; fi
|
||||
sleep 2
|
||||
done
|
||||
printf 'Central /healthz: HTTP 200\n'
|
||||
|
||||
BASE_URL="$base_url" ACCEPTANCE_ADMIN_PASSWORD="$admin_password" python3 - <<'PY'
|
||||
import json, os, secrets, urllib.error, urllib.request
|
||||
base=os.environ['BASE_URL']
|
||||
def post(path, body, token=None):
|
||||
headers={'Content-Type':'application/json'}
|
||||
if token: headers['Authorization']='Bearer '+token
|
||||
req=urllib.request.Request(base+path, data=json.dumps(body).encode(), headers=headers, method='POST')
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=20) as response:
|
||||
return response.status, response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, error.read()
|
||||
status, _=post('/api/auth/bootstrap-admin', {'email':'acceptance-admin@heimdall.test','password':os.environ['ACCEPTANCE_ADMIN_PASSWORD'],'displayName':'Disposable Acceptance Admin'})
|
||||
if status != 200: raise SystemExit(f'Admin bootstrap failed: HTTP {status}')
|
||||
status, payload=post('/api/auth/login', {'email':'acceptance-admin@heimdall.test','password':os.environ['ACCEPTANCE_ADMIN_PASSWORD']})
|
||||
if status != 200:
|
||||
raise SystemExit(f'Admin login failed: HTTP {status}')
|
||||
admin=json.loads(payload)['accessToken']
|
||||
for role in ('Viewer','Supervisor'):
|
||||
email=f'{role.lower()}-{secrets.token_hex(8)}@heimdall.test'
|
||||
password='CreateLogin!'+secrets.token_urlsafe(18)+'A1'
|
||||
status, payload=post('/api/users', {'email':email,'password':password,'displayName':f'Acceptance {role}','roles':[role]}, admin)
|
||||
if status not in (200,201): raise SystemExit(f'{role} create failed: HTTP {status}')
|
||||
user_id=json.loads(payload)['id']
|
||||
status,_=post(f'/api/users/{user_id}/confirm-email', {}, admin)
|
||||
if status != 200: raise SystemExit(f'{role} email confirmation failed: HTTP {status}')
|
||||
status,payload=post('/api/auth/login', {'email':email,'password':password})
|
||||
if status != 200: raise SystemExit(f'{role} first login failed: HTTP {status}')
|
||||
if not json.loads(payload).get('accessToken'): raise SystemExit(f'{role} login returned no access token')
|
||||
print(f'{role}: create, admin email confirmation, and first login passed (HTTP 200)')
|
||||
PY
|
||||
@@ -56,6 +56,64 @@ public class UserManagementTests : E2ETestBase
|
||||
body.ShouldContain("E2E Viewer");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Supervisor", true)]
|
||||
[InlineData("Supervisor", false)]
|
||||
[InlineData("Viewer", true)]
|
||||
[InlineData("Viewer", false)]
|
||||
public async Task User_created_from_dialog_can_log_in_with_submitted_password_after_email_confirmation(
|
||||
string role, bool selectRoleBeforePassword)
|
||||
{
|
||||
await LoginViaUiAsync();
|
||||
await GotoWithCircuitAsync("/users");
|
||||
await Page.WaitForSelectorAsync("text=Nouvel utilisateur", new() { Timeout = 20000 });
|
||||
await Page.ClickAsync("text=Nouvel utilisateur");
|
||||
|
||||
var dialog = Page.Locator(".mud-dialog");
|
||||
await dialog.WaitForAsync(new() { Timeout = 10000 });
|
||||
var email = $"e2e-{role.ToLowerInvariant()}-{Guid.NewGuid():N}@heimdall.test";
|
||||
var password = "FirstLoginPass123!";
|
||||
await dialog.Locator("input[autocomplete='email']").FillAsync(email);
|
||||
await dialog.Locator("input[autocomplete='name']").FillAsync($"E2E {role}");
|
||||
|
||||
if (selectRoleBeforePassword)
|
||||
await SelectCreateRoleAsync(dialog, role);
|
||||
|
||||
await dialog.Locator("input[autocomplete='new-password']").FillAsync(password);
|
||||
|
||||
if (!selectRoleBeforePassword)
|
||||
await SelectCreateRoleAsync(dialog, role);
|
||||
|
||||
await dialog.Locator("button:has-text('Créer')").ClickAsync();
|
||||
await dialog.WaitForAsync(new() { State = WaitForSelectorState.Detached, Timeout = 15000 });
|
||||
|
||||
var token = await LoginViaApiAsync();
|
||||
using var admin = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
admin.DefaultRequestHeaders.Authorization = new("Bearer", token);
|
||||
var row = Page.Locator($"tr:has-text('{email}')");
|
||||
await row.WaitForAsync(new() { Timeout = 15000 });
|
||||
await row.GetByRole(AriaRole.Button, new() { Name = "Confirmer l’email", Exact = true }).ClickAsync();
|
||||
|
||||
using var login = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
var response = await login.PostAsJsonAsync("/api/auth/login", new { email, password });
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.OK,
|
||||
$"A {role} account created with role selected {(selectRoleBeforePassword ? "before" : "after")} its password should authenticate after admin email confirmation.");
|
||||
var body = await response.Content.ReadFromJsonAsync<System.Text.Json.JsonElement>();
|
||||
body.GetProperty("accessToken").GetString().ShouldNotBeNullOrWhiteSpace();
|
||||
|
||||
using var cleanup = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
cleanup.DefaultRequestHeaders.Authorization = new("Bearer", token);
|
||||
var deleteResponse = await cleanup.DeleteAsync($"/api/users/{body.GetProperty("user").GetProperty("id").GetString()}");
|
||||
deleteResponse.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.NoContent);
|
||||
}
|
||||
|
||||
private static async Task SelectCreateRoleAsync(ILocator dialog, string role)
|
||||
{
|
||||
await dialog.Locator(".mud-input-control.mud-select").ClickAsync();
|
||||
await dialog.Page.Locator(".mud-popover-open .mud-list-item")
|
||||
.Filter(new() { HasText = role }).ClickAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task New_user_can_log_in_with_viewer_role()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user