entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
#!/usr/bin/env pwsh

# ======================
# Script Init
# ======================

# Ensure we're running in PowerShell Core
if (-not ($PSVersionTable.PSEdition -eq "Core"))
{
    Write-Host "This script requires PowerShell Core. Please install it first."
    exit 1
}

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

# ======================
# Variables and Constants
# ======================

# Set default log level (DEBUG, INFO, WARNING, ERROR)
$Script:LOG_LEVEL = if ($env:LOG_LEVEL)
{ $env:LOG_LEVEL
} else
{ "INFO"
}

# Required environment variables
$Script:SUITE = if ($env:SUITE)
{ $env:SUITE
} else
{ ""
}
$Script:WORKSPACE_DIR = if ($env:WORKSPACE_DIR)
{ $env:WORKSPACE_DIR
} else
{ ""
}

# Optional environment variables
$Script:CARGO_BUILD_PROFILE = if ($env:CARGO_BUILD_PROFILE)
{ $env:CARGO_BUILD_PROFILE
} else
{ "dev"
}
$Script:CARGO_FEATURES = if ($env:CARGO_FEATURES)
{ $env:CARGO_FEATURES
} else
{ ""
}
$Script:RUST_LOG = if ($env:RUST_LOG)
{ $env:RUST_LOG
} else
{ ""
}
$Script:CARGO_TEST_THREADS = if ($env:CARGO_TEST_THREADS)
{ $env:CARGO_TEST_THREADS
} else
{ ""
}
# Which static-analysis scanner to run when SUITE is "security-scan":
# semgrep | kics | secrets.
$Script:SCAN = if ($env:SCAN)
{ $env:SCAN
} else
{ ""
}

# Constants
$Script:VALID_SUITES = @("unit", "integration", "doc", "clippy", "fmt", "deny", "security-scan")

# Log file name for this script
$Script:LOG_FILE_NAME = "entropy_auth_test.log"

# ======================
# Shared Functions
# ======================

. "$PSScriptRoot/common.ps1"

# ======================
# Function Definitions
# ======================

# Ensure all mandatory environment variables are present
function Test-EnvironmentVariables
{
    $absent = @()

    if ([string]::IsNullOrEmpty($Script:SUITE))
    { $absent += "SUITE"
    }
    if ([string]::IsNullOrEmpty($Script:WORKSPACE_DIR))
    { $absent += "WORKSPACE_DIR"
    }

    if ($absent.Count -gt 0)
    {
        Write-Log -LogLevel "ERROR" -LogMessage "Missing required environment variables:"
        foreach ($v in $absent)
        {
            Write-Log -LogLevel "ERROR" -LogMessage "  - $v"
        }
        return $false
    }

    # Validate suite is a known value
    if ($Script:SUITE -notin $Script:VALID_SUITES)
    {
        Write-Log -LogLevel "ERROR" -LogMessage "SUITE must be one of: $($Script:VALID_SUITES -join ', '). Got: '$($Script:SUITE)'"
        return $false
    }

    Write-Log -LogLevel "INFO" -LogMessage "All required environment variables are present"
    return $true
}

# Build common cargo arguments from configuration
function Get-CargoBaseArgs
{
    $cargoArgs = @()

    if ($Script:CARGO_BUILD_PROFILE -ne "dev")
    {
        $cargoArgs += "--profile"
        $cargoArgs += $Script:CARGO_BUILD_PROFILE
    }

    if (-not [string]::IsNullOrEmpty($Script:CARGO_FEATURES))
    {
        $cargoArgs += "--features"
        $cargoArgs += $Script:CARGO_FEATURES
    }

    return $cargoArgs
}

# Run unit tests via cargo test (library and inline tests)
function Invoke-UnitTests
{
    Start-OperationTiming -Operation "unit_tests"

    Write-Log -LogLevel "INFO" -LogMessage "=== Running Unit Tests ==="

    $cargoArgs = @("test", "--lib") + (Get-CargoBaseArgs)

    # Limit test threads if configured (required for tests that mutate env vars)
    if (-not [string]::IsNullOrEmpty($Script:CARGO_TEST_THREADS))
    {
        $cargoArgs += "--"
        $cargoArgs += "--test-threads=$($Script:CARGO_TEST_THREADS)"
    }

    Write-Log -LogLevel "DEBUG" -LogMessage "Working directory: $($Script:WORKSPACE_DIR)"
    Write-Log -LogLevel "DEBUG" -LogMessage "Command: cargo $($cargoArgs -join ' ')"

    Push-Location $Script:WORKSPACE_DIR
    try
    {
        Write-Log -LogLevel "INFO" -LogMessage "Running cargo test --lib..."
        & cargo @cargoArgs 2>&1 | ForEach-Object {
            $line = "$_"
            if (-not [string]::IsNullOrWhiteSpace($line))
            {
                if ($line -match 'test result:|FAILED|error\[' )
                {
                    Write-Log -LogLevel "INFO" -LogMessage "[cargo test] $line"
                } else
                {
                    Write-Log -LogLevel "DEBUG" -LogMessage "[cargo test] $line"
                }
            }
        }

        if ($LASTEXITCODE -ne 0)
        {
            Write-Log -LogLevel "ERROR" -LogMessage "Unit tests failed with exit code $LASTEXITCODE"
            return $false
        }

        Write-Log -LogLevel "INFO" -LogMessage "Unit tests passed" -OperationName "unit_tests"
        return $true
    } finally
    {
        Pop-Location
        Stop-OperationTiming -Operation "unit_tests"
    }
}

# Run integration tests via cargo test --test (tests/ directory)
function Invoke-IntegrationTests
{
    Start-OperationTiming -Operation "integration_tests"

    Write-Log -LogLevel "INFO" -LogMessage "=== Running Integration Tests ==="

    $cargoArgs = @("test", "--test", "*") + (Get-CargoBaseArgs)

    if (-not [string]::IsNullOrEmpty($Script:CARGO_TEST_THREADS))
    {
        $cargoArgs += "--"
        $cargoArgs += "--test-threads=$($Script:CARGO_TEST_THREADS)"
    }

    Write-Log -LogLevel "DEBUG" -LogMessage "Working directory: $($Script:WORKSPACE_DIR)"
    Write-Log -LogLevel "DEBUG" -LogMessage "Command: cargo $($cargoArgs -join ' ')"

    Push-Location $Script:WORKSPACE_DIR
    try
    {
        Write-Log -LogLevel "INFO" -LogMessage "Running cargo test --test '*'..."
        & cargo @cargoArgs 2>&1 | ForEach-Object {
            $line = "$_"
            if (-not [string]::IsNullOrWhiteSpace($line))
            {
                if ($line -match 'test result:|FAILED|error\[')
                {
                    Write-Log -LogLevel "INFO" -LogMessage "[cargo test] $line"
                } else
                {
                    Write-Log -LogLevel "DEBUG" -LogMessage "[cargo test] $line"
                }
            }
        }

        if ($LASTEXITCODE -ne 0)
        {
            Write-Log -LogLevel "ERROR" -LogMessage "Integration tests failed with exit code $LASTEXITCODE"
            return $false
        }

        Write-Log -LogLevel "INFO" -LogMessage "Integration tests passed" -OperationName "integration_tests"
        return $true
    } finally
    {
        Pop-Location
        Stop-OperationTiming -Operation "integration_tests"
    }
}

# Run documentation tests via cargo test --doc
function Invoke-DocTests
{
    Start-OperationTiming -Operation "doc_tests"

    Write-Log -LogLevel "INFO" -LogMessage "=== Running Documentation Tests ==="

    $cargoArgs = @("test", "--doc") + (Get-CargoBaseArgs)

    Write-Log -LogLevel "DEBUG" -LogMessage "Working directory: $($Script:WORKSPACE_DIR)"
    Write-Log -LogLevel "DEBUG" -LogMessage "Command: cargo $($cargoArgs -join ' ')"

    Push-Location $Script:WORKSPACE_DIR
    try
    {
        Write-Log -LogLevel "INFO" -LogMessage "Running cargo test --doc..."
        & cargo @cargoArgs 2>&1 | ForEach-Object {
            $line = "$_"
            if (-not [string]::IsNullOrWhiteSpace($line))
            {
                if ($line -match 'test result:|FAILED|error\[')
                {
                    Write-Log -LogLevel "INFO" -LogMessage "[cargo test] $line"
                } else
                {
                    Write-Log -LogLevel "DEBUG" -LogMessage "[cargo test] $line"
                }
            }
        }

        if ($LASTEXITCODE -ne 0)
        {
            Write-Log -LogLevel "ERROR" -LogMessage "Documentation tests failed with exit code $LASTEXITCODE"
            return $false
        }

        Write-Log -LogLevel "INFO" -LogMessage "Documentation tests passed" -OperationName "doc_tests"
        return $true
    } finally
    {
        Pop-Location
        Stop-OperationTiming -Operation "doc_tests"
    }
}

# Run clippy lints (cargo clippy with warnings as errors)
function Invoke-ClippyCheck
{
    Start-OperationTiming -Operation "clippy_check"

    Write-Log -LogLevel "INFO" -LogMessage "=== Running Clippy Lints ==="

    # Lint every feature by default (overridable via env) so the optional
    # asym-jwt/oidc/saml/ssh-keys code paths are covered, not just the default
    # feature set.
    if ([string]::IsNullOrEmpty($Script:CARGO_FEATURES))
    { $Script:CARGO_FEATURES = "saml,oidc,ssh-keys,asym-jwt"
    }

    $cargoArgs = @("clippy", "--all-targets") + (Get-CargoBaseArgs) + @("--", "-D", "warnings", "-W", "clippy::pedantic")

    Write-Log -LogLevel "DEBUG" -LogMessage "Working directory: $($Script:WORKSPACE_DIR)"
    Write-Log -LogLevel "DEBUG" -LogMessage "Command: cargo $($cargoArgs -join ' ')"

    Push-Location $Script:WORKSPACE_DIR
    try
    {
        Write-Log -LogLevel "INFO" -LogMessage "Running cargo clippy --all-targets -- -D warnings -W clippy::pedantic..."
        & cargo @cargoArgs 2>&1 | ForEach-Object {
            $line = "$_"
            if (-not [string]::IsNullOrWhiteSpace($line))
            {
                if ($line -match 'warning:|error\[')
                {
                    Write-Log -LogLevel "INFO" -LogMessage "[clippy] $line"
                } else
                {
                    Write-Log -LogLevel "DEBUG" -LogMessage "[clippy] $line"
                }
            }
        }

        if ($LASTEXITCODE -ne 0)
        {
            Write-Log -LogLevel "ERROR" -LogMessage "Clippy check failed with exit code $LASTEXITCODE"
            return $false
        }

        Write-Log -LogLevel "INFO" -LogMessage "Clippy check passed — zero warnings" -OperationName "clippy_check"
        return $true
    } finally
    {
        Pop-Location
        Stop-OperationTiming -Operation "clippy_check"
    }
}

# Run formatting check (cargo fmt --check)
function Invoke-FmtCheck
{
    Start-OperationTiming -Operation "fmt_check"

    Write-Log -LogLevel "INFO" -LogMessage "=== Running Formatting Check ==="

    $cargoArgs = @("fmt", "--", "--check")

    Write-Log -LogLevel "DEBUG" -LogMessage "Working directory: $($Script:WORKSPACE_DIR)"
    Write-Log -LogLevel "DEBUG" -LogMessage "Command: cargo $($cargoArgs -join ' ')"

    Push-Location $Script:WORKSPACE_DIR
    try
    {
        Write-Log -LogLevel "INFO" -LogMessage "Running cargo fmt -- --check..."
        & cargo @cargoArgs 2>&1 | ForEach-Object {
            $line = "$_"
            if (-not [string]::IsNullOrWhiteSpace($line))
            {
                if ($line -match 'Diff in|should be')
                {
                    Write-Log -LogLevel "INFO" -LogMessage "[fmt] $line"
                } else
                {
                    Write-Log -LogLevel "DEBUG" -LogMessage "[fmt] $line"
                }
            }
        }

        if ($LASTEXITCODE -ne 0)
        {
            Write-Log -LogLevel "ERROR" -LogMessage "Formatting check failed with exit code $LASTEXITCODE"
            return $false
        }

        Write-Log -LogLevel "INFO" -LogMessage "Formatting check passed — all files formatted" -OperationName "fmt_check"
        return $true
    } finally
    {
        Pop-Location
        Stop-OperationTiming -Operation "fmt_check"
    }
}

# Run supply-chain audit (cargo-deny: advisories, licenses, bans, sources).
# --all-features so optional deps (rsa via asym-jwt, …) are audited and the
# documented advisory ignores in deny.toml are exercised.
function Invoke-DenyCheck
{
    Start-OperationTiming -Operation "deny_check"

    Write-Log -LogLevel "INFO" -LogMessage "=== Running Supply-Chain Audit (cargo-deny) ==="

    # Install on demand; the build-agent image does not ship cargo-deny.
    if (-not (Get-Command cargo-deny -ErrorAction SilentlyContinue))
    {
        Write-Log -LogLevel "INFO" -LogMessage "Installing cargo-deny..."
        & cargo install cargo-deny --locked
    }

    Push-Location $Script:WORKSPACE_DIR
    try
    {
        Write-Log -LogLevel "INFO" -LogMessage "Running cargo deny --all-features check..."
        & cargo deny --all-features check advisories licenses bans sources 2>&1 | ForEach-Object {
            $line = "$_"
            if (-not [string]::IsNullOrWhiteSpace($line))
            { Write-Log -LogLevel "DEBUG" -LogMessage "[cargo-deny] $line"
            }
        }
        if ($LASTEXITCODE -ne 0)
        {
            Write-Log -LogLevel "ERROR" -LogMessage "cargo-deny check failed with exit code $LASTEXITCODE"
            return $false
        }
        Write-Log -LogLevel "INFO" -LogMessage "cargo-deny check passed" -OperationName "deny_check"
        return $true
    } finally
    {
        Pop-Location
        Stop-OperationTiming -Operation "deny_check"
    }
}

# ======================
# Security Scanners (SAST)
# ======================
# Ported from the simple-finance test runner. Each scanner self-installs into
# the (Debian) test-agent on demand and emits a GitLab report artifact.

function Get-LinuxArch
{
    # Release archives disagree on arch naming: kics uses amd64/arm64,
    # gitleaks uses x64/arm64. Pass the project's convention.
    param(
        [ValidateSet('amd64', 'x64', 'x86_64')]
        [string]$AmdConvention = 'amd64',
        [ValidateSet('arm64', 'aarch64')]
        [string]$ArmConvention = 'arm64'
    )
    $m = (& uname -m).Trim()
    switch ($m)
    {
        'x86_64'
        { return $AmdConvention
        }
        'aarch64'
        { return $ArmConvention
        }
        'arm64'
        { return $ArmConvention
        }
        default
        { throw "Unsupported architecture: $m"
        }
    }
}

function Install-Semgrep
{
    if (Get-Command semgrep -ErrorAction SilentlyContinue)
    { return
    }
    Write-Log -LogLevel "INFO" -LogMessage "Installing semgrep via pip (venv)"
    # venv avoids PEP 668 "externally managed" rejection on newer Debian and
    # keeps the agent's site-packages clean; symlink into PATH for callers.
    $venv = "/opt/semgrep-venv"
    if (-not (Test-Path "$venv/bin/semgrep"))
    {
        & apt-get update -qq
        & apt-get install -y --no-install-recommends python3-venv python3-pip
        if ($LASTEXITCODE -ne 0)
        { throw "python3-venv install failed"
        }
        & python3 -m venv $venv
        if ($LASTEXITCODE -ne 0)
        { throw "python3 -m venv failed"
        }
        & "$venv/bin/pip" install --quiet --upgrade pip
        & "$venv/bin/pip" install --quiet semgrep
        if ($LASTEXITCODE -ne 0)
        { throw "semgrep install failed"
        }
    }
    & ln -sf "$venv/bin/semgrep" /usr/local/bin/semgrep
}

function Install-Kics
{
    # The release tarball ships the binary alone; the rule set lives in the
    # source repo, so download the binary AND shallow-clone the matching tag.
    $kicsBin = "/opt/kics/kics"
    $kicsSrc = "/opt/kics/src"
    $version = "2.1.20"
    if ((Test-Path $kicsBin) -and (Test-Path "$kicsSrc/assets/queries") -and (Get-Command kics -ErrorAction SilentlyContinue))
    {
        return
    }
    Write-Log -LogLevel "INFO" -LogMessage "Installing kics $version (binary + queries)"
    $arch = Get-LinuxArch -AmdConvention 'amd64' -ArmConvention 'arm64'
    $url = "https://github.com/Checkmarx/kics/releases/download/v$version/kics_${version}_linux_${arch}.tar.gz"
    New-Item -ItemType Directory -Path "/opt/kics" -Force | Out-Null
    $tar = "/tmp/kics-$version-$arch.tar.gz"
    Invoke-WebRequest -Uri $url -OutFile $tar
    & tar -xzf $tar -C "/opt/kics"
    Remove-Item -Force $tar
    & ln -sf $kicsBin /usr/local/bin/kics
    if (-not (Test-Path "$kicsSrc/assets/queries"))
    {
        Write-Log -LogLevel "INFO" -LogMessage "Cloning kics queries tag v$version"
        & git clone --quiet --depth=1 --branch "v$version" `
            "https://github.com/Checkmarx/kics.git" $kicsSrc
        if ($LASTEXITCODE -ne 0)
        { throw "kics queries clone failed"
        }
    }
}

function Install-Gitleaks
{
    if (Get-Command gitleaks -ErrorAction SilentlyContinue)
    { return
    }
    Write-Log -LogLevel "INFO" -LogMessage "Installing gitleaks binary"
    $version = "8.30.1"
    $arch = Get-LinuxArch -AmdConvention 'x64' -ArmConvention 'arm64'
    $url = "https://github.com/gitleaks/gitleaks/releases/download/v$version/gitleaks_${version}_linux_${arch}.tar.gz"
    $tmpRoot = if ($env:TMPDIR)
    { $env:TMPDIR
    } else
    { "/tmp"
    }
    $tmp = New-Item -ItemType Directory -Path "$tmpRoot/gitleaks-install-$([guid]::NewGuid())" -Force
    try
    {
        $tar = Join-Path $tmp.FullName 'gitleaks.tar.gz'
        Invoke-WebRequest -Uri $url -OutFile $tar
        & tar -xzf $tar -C $tmp.FullName
        Move-Item -Force (Join-Path $tmp.FullName 'gitleaks') /usr/local/bin/gitleaks
    } finally
    {
        Remove-Item -Recurse -Force $tmp.FullName -ErrorAction SilentlyContinue
    }
}

# Run a single static-analysis scanner (selected by $Script:SCAN) and emit a
# GitLab report artifact. Findings fail the job.
function Invoke-SecurityScan
{
    Start-OperationTiming -Operation "security_scan"
    if ([string]::IsNullOrEmpty($Script:SCAN))
    {
        Write-Log -LogLevel "ERROR" -LogMessage "SCAN env var is required (semgrep | kics | secrets)"
        return $false
    }
    Write-Log -LogLevel "INFO" -LogMessage "=== Running security scan: $($Script:SCAN) ==="

    Push-Location $Script:WORKSPACE_DIR
    try
    {
        switch ($Script:SCAN)
        {
            'semgrep'
            {
                Install-Semgrep
                & semgrep ci --gitlab-sast --output=gl-sast-report.json --error
                if ($LASTEXITCODE -ne 0)
                { throw "semgrep findings present"
                }
            }
            'kics'
            {
                Install-Kics
                # No kics.config in this crate (pure Rust, no IaC); rely on the
                # bundled rule set and only fail on HIGH-severity findings.
                & kics scan -p . -o . `
                    -q /opt/kics/src/assets/queries `
                    -b /opt/kics/src/assets/libraries `
                    --report-formats glsast `
                    --output-name results `
                    --fail-on high
                $kicsExit = $LASTEXITCODE
                if (Test-Path 'results.glsast.json')
                {
                    Move-Item -Force 'results.glsast.json' 'gl-sast-report.json'
                }
                if ($kicsExit -ne 0)
                { throw "kics findings present (HIGH severity)"
                }
            }
            'secrets'
            {
                Install-Gitleaks
                $gitleaksArgs = @(
                    "detect", "--source=.",
                    "--report-path=gl-secret-detection-report.json",
                    "--report-format=json", "--no-banner", "--redact"
                )
                # Use a repo .gitleaks.toml when present; otherwise gitleaks'
                # built-in rules.
                if (Test-Path '.gitleaks.toml')
                { $gitleaksArgs += "--config=.gitleaks.toml"
                }
                & gitleaks @gitleaksArgs
                if ($LASTEXITCODE -ne 0)
                { throw "gitleaks findings present"
                }
            }
            default
            {
                throw "Unknown SCAN: '$($Script:SCAN)'. Expected one of: semgrep, kics, secrets."
            }
        }
    } catch
    {
        Write-Log -LogLevel "ERROR" -LogMessage "Security scan failed: $_"
        return $false
    } finally
    {
        Pop-Location
        Stop-OperationTiming -Operation "security_scan"
    }

    Write-Log -LogLevel "INFO" -LogMessage "Security scan passed: $($Script:SCAN)" -OperationName "security_scan"
    return $true
}

# ======================
# Main Script Execution
# ======================

# Display Banner
Write-Host '
    ##############################################################################################
    #                                                                                            #
    #                    Entropy Softworks — entropy-auth Test Automation                        #
    #                                                                                            #
    ##############################################################################################

                                    === Overview ===

    Runs Rust test suites for the entropy-auth crate based on the SUITE
    environment variable:

    - unit        : Library and inline unit tests (cargo test --lib)
    - integration : Integration tests from the tests/ directory (cargo test --test)
    - doc         : Documentation example tests (cargo test --doc)
    - clippy      : Lint analysis with warnings as errors (cargo clippy -D warnings)
    - fmt         : Formatting check (cargo fmt -- --check)

    === Environment Variables ===
    Required: SUITE, WORKSPACE_DIR
    Optional: CARGO_BUILD_PROFILE, CARGO_FEATURES, CARGO_TEST_THREADS,
              RUST_LOG, LOG_LEVEL

'

Start-OperationTiming -Operation "total_test"

# Validate environment variables
if (-not (Test-EnvironmentVariables))
{
    Write-Log -LogLevel "ERROR" -LogMessage "Environment validation failed — aborting"
    exit 1
}

# Verify required tooling
if (-not (Test-ToolInstallation -ToolName "cargo"))
{
    Write-Log -LogLevel "ERROR" -LogMessage "cargo is required but not available"
    exit 1
}

# Log configuration summary
Write-Log -LogLevel "INFO" -LogMessage "Configuration:"
Write-Log -LogLevel "INFO" -LogMessage "  Suite                : $($Script:SUITE)"
Write-Log -LogLevel "INFO" -LogMessage "  Workspace            : $($Script:WORKSPACE_DIR)"
Write-Log -LogLevel "INFO" -LogMessage "  Build Profile        : $($Script:CARGO_BUILD_PROFILE)"
if (-not [string]::IsNullOrEmpty($Script:CARGO_FEATURES))
{
    Write-Log -LogLevel "INFO" -LogMessage "  Features             : $($Script:CARGO_FEATURES)"
}
if (-not [string]::IsNullOrEmpty($Script:CARGO_TEST_THREADS))
{
    Write-Log -LogLevel "INFO" -LogMessage "  Test Threads         : $($Script:CARGO_TEST_THREADS)"
}

# Set RUST_LOG if provided
if (-not [string]::IsNullOrEmpty($Script:RUST_LOG))
{
    $env:RUST_LOG = $Script:RUST_LOG
    Write-Log -LogLevel "DEBUG" -LogMessage "RUST_LOG set to: $($Script:RUST_LOG)"
}

# Run the requested test suite
$testResult = $false

switch ($Script:SUITE)
{
    "unit"
    {
        $testResult = Invoke-UnitTests
    }
    "integration"
    {
        $testResult = Invoke-IntegrationTests
    }
    "doc"
    {
        $testResult = Invoke-DocTests
    }
    "clippy"
    {
        $testResult = Invoke-ClippyCheck
    }
    "fmt"
    {
        $testResult = Invoke-FmtCheck
    }
    "deny"
    {
        $testResult = Invoke-DenyCheck
    }
    "security-scan"
    {
        $testResult = Invoke-SecurityScan
    }
}

# Done
Stop-OperationTiming -Operation "total_test"

if ($testResult)
{
    Write-Log -LogLevel "INFO" -LogMessage "Test suite completed successfully" -OperationName "total_test"
    Show-TimingSummary
    exit 0
} else
{
    Write-Log -LogLevel "ERROR" -LogMessage "Test suite failed"
    Show-TimingSummary
    exit 1
}