All files / core/blong-browser/src/components/TestRun/fixtures sessionFlow.ts

84.74% Statements 50/59
83.33% Branches 30/36
82.35% Functions 14/17
83.63% Lines 46/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                  4x 4x   4x                           4x                                                                                         44x 156x                           164x                                     44x                                       131x       4x                         4x                                                                                                                     4x                                                                                                                                                         24x 24x       4x 4x 4x         4x                                             4x                     4x                     4x           20x               5x       5x                                                                                                   3x 3x 3x 3x 3x 3x   3x   18x 120x   120x   120x 120x 120x 120x                         120x 120x 120x 120x   18x   120x 3x                             21x                              
/**
 * Phase 1 fixtures for the TestRun console.
 *
 * `sessionFlow` is hand-authored from
 * `realm/blong-access/server/test/test/testSessionFlow.ts`: 11 steps, two dependency chains, and
 * several independent steps running in parallel. A failure variant and a synthetic dense variant
 * cover the states the console must survive.
 */
import type {
    ITestAssertionModel,
    ITestEdgeModel,
    ITestRunModel,
    ITestRunRecording,
    ITestStepModel,
} from '../../../types/testRun.js';
import {deriveTestRun, recordingFromRun} from '../testRunModel.js';
 
const BASE = 1_760_000_000_000;
const SOURCE = 'realm/blong-access/server/test/test/testSessionFlow.ts';
 
const SOURCE_LINES: Record<string, number> = {
    login: 42,
    verifySession: 61,
    refreshToken: 80,
    reuseDetection: 101,
    revokedSession: 120,
    explicitClose: 141,
    inactivity: 161,
    cleanup: 180,
    auditLog: 199,
    loginActionRequired: 218,
    userInactiveRefusesRenewal: 237,
};
 
const ASSERTION_MESSAGES: Record<string, string[]> = {
    login: [
        'the session id is a ULID',
        'the access token has three segments',
        'the token expiry is in the future',
        'the permissions include accessTestPrivate',
        'the refresh token is opaque',
    ],
    verifySession: ['the session is active'],
    refreshToken: [
        'the refresh token rotated',
        'the old refresh token is gone',
        'the new access token is signed',
        'the session id is unchanged',
        'the rotation flag is set',
        'the reuse window is closed',
    ],
    reuseDetection: ['the reused token was refused', 'the failure is recorded'],
    explicitClose: [
        'the session is closed',
        'the access token is refused after close',
        'a second close is idempotent',
        'the close event is logged',
        'the refresh token is discarded',
        'the session row is gone',
    ],
    inactivity: ['the session expires after idle', 'the refresh is refused after expiry'],
    cleanup: ['the closed session left the table', 'the audit trail keeps the close event'],
    auditLog: [
        'the close event is in the audit log',
        'the audit entry names the session',
        'the audit entry is signed',
        'the audit write is durable',
        'the audit log is append only',
    ],
    loginActionRequired: ['the login action is required', 'the action is actionable'],
    userInactiveRefusesRenewal: [
        'the inactive user is refused',
        'the refusal names the user',
        'the refusal is recorded',
        'the refusal does not leak a token',
    ],
};
 
function assertionLogFor(name: string, start: number, count: number): ITestAssertionModel[] {
    const messages = ASSERTION_MESSAGES[name] ?? [];
    return Array.from({length: count}, (_, index) => ({
        message: messages[index] ?? `${name} assertion ${index + 1} passed`,
        passed: true,
        timestamp: BASE + start + index,
        source: {
            file: SOURCE,
            line: (SOURCE_LINES[name] ?? 1) + index + 2,
            column: 9,
            symbol: 'assert',
        },
    }));
}
 
function step(partial: Partial<ITestStepModel> & {stepName: string}): ITestStepModel {
    return {
        displayName: partial.stepName,
        groupPath: [],
        status: 'completed',
        queuedAt: BASE,
        dependencies: [],
        dependents: [],
        assertions: {total: 0, threw: 0},
        ...partial,
    };
}
 
function timed(
    name: string,
    start: number,
    end: number,
    assertions: number,
    extra: Partial<ITestStepModel> = {},
): ITestStepModel {
    return step({
        stepName: name,
        startedAt: BASE + start,
        endedAt: BASE + end,
        queueTime: start,
        executionTime: end - start,
        duration: end - start,
        assertions: {total: assertions, threw: 0},
        sourceLocation: {
            file: SOURCE,
            line: SOURCE_LINES[name] ?? 1,
            column: 5,
            symbol: name,
        },
        assertionLog: assertions > 0 ? assertionLogFor(name, start, assertions) : undefined,
        ...extra,
    });
}
 
function edge(from: string, to: string, property = to): ITestEdgeModel {
    return {id: `${from}->${to}:${property}`, from, to, property, status: 'done'};
}
 
function rawSessionFlow(): ITestRunModel {
    const order = [
        'login',
        'verifySession',
        'refreshToken',
        'reuseDetection',
        'revokedSession',
        'explicitClose',
        'inactivity',
        'cleanup',
        'auditLog',
        'loginActionRequired',
        'userInactiveRefusesRenewal',
    ];
    const steps: Record<string, ITestStepModel> = {
        login: timed('login', 0, 412, 5, {
            result: {
                sessionId: '0198f0c4-6d1a-7a1e-9a52-4b1f0d3f5a01',
                accessToken: 'eyJhbGciOiJIUzI1NiJ9.…',
                permissions: ['accessTestPrivate'],
            },
            progress: [
                {
                    kind: 'region',
                    discriminator: 'auth-method',
                    candidates: ['password', 'refresh'],
                    chosen: 'password',
                    values: {username: 'testUser'},
                },
                {
                    kind: 'point',
                    name: 'session-created',
                    data: {authMethod: 'password', permissions: 1},
                    timestamp: BASE + 380,
                    regions: [
                        {
                            discriminator: 'auth-method',
                            candidates: ['password', 'refresh'],
                            chosen: 'password',
                        },
                    ],
                },
            ],
        }),
        verifySession: timed('verifySession', 413, 509, 1, {
            dependencies: ['login'],
            result: {userId: '2f1c5a44-0f3e-4d2a-8f4b-6c7d8e9f0a11'},
        }),
        refreshToken: timed('refreshToken', 510, 618, 6, {
            dependencies: ['verifySession'],
            result: {sessionId: '0198f0c4-6d1a-7a1e-9a52-4b1f0d3f5a01', rotated: true},
        }),
        reuseDetection: timed('reuseDetection', 619, 704, 2, {
            dependencies: ['refreshToken'],
            progress: [
                {
                    kind: 'point',
                    name: 'reuse-detected',
                    data: {sessionId: '0198f0c4-6d1a-7a1e-9a52-4b1f0d3f5a01'},
                    timestamp: BASE + 660,
                },
            ],
        }),
        revokedSession: timed('revokedSession', 705, 812, 4, {
            dependencies: ['reuseDetection'],
        }),
        explicitClose: timed('explicitClose', 0, 201, 6),
        inactivity: timed('inactivity', 0, 96, 2),
        cleanup: timed('cleanup', 97, 133, 2, {dependencies: ['inactivity']}),
        auditLog: timed('auditLog', 30, 260, 5),
        loginActionRequired: timed('loginActionRequired', 10, 70, 2),
        userInactiveRefusesRenewal: timed('userInactiveRefusesRenewal', 40, 480, 4),
    };
    return deriveTestRun({
        runId: 'run-session-flow',
        name: 'session flow',
        method: 'test.session.flow',
        host: 'browser',
        status: 'completed',
        startedAt: BASE,
        endedAt: BASE + 812,
        concurrency: 10,
        order,
        steps,
        edges: [
            edge('verifySession', 'login'),
            edge('refreshToken', 'verifySession'),
            edge('reuseDetection', 'refreshToken'),
            edge('revokedSession', 'reuseDetection'),
            edge('cleanup', 'inactivity'),
        ],
        groups: [],
        counts: {total: 0, pending: 0, running: 0, completed: 0, failed: 0},
        assertions: {total: 0, threw: 0},
        criticalPath: [
            'login',
            'verifySession',
            'refreshToken',
            'reuseDetection',
            'revokedSession',
        ],
        logs: [
            {
                timestamp: BASE,
                level: 'info',
                message: 'run started',
                source: {file: SOURCE, line: 39, column: 9},
            },
            {
                timestamp: BASE + 4,
                level: 'debug',
                message: 'login dispatched',
                stepName: 'login',
                source: {file: SOURCE, line: 44, column: 9},
            },
            {
                timestamp: BASE + 380,
                level: 'info',
                message: 'session-created',
                stepName: 'login',
                source: {file: SOURCE, line: 55, column: 9},
            },
            {
                timestamp: BASE + 414,
                level: 'debug',
                message: 'session verified',
                stepName: 'verifySession',
                source: {file: SOURCE, line: 65, column: 9},
            },
            {
                timestamp: BASE + 620,
                level: 'warn',
                message: 'rotated refresh token reused',
                stepName: 'reuseDetection',
                source: {file: SOURCE, line: 105, column: 9},
            },
            {
                timestamp: BASE + 813,
                level: 'info',
                message: 'run completed',
                source: {file: SOURCE, line: 260, column: 9},
            },
        ],
        source: {file: SOURCE, recordedAt: BASE},
    });
}
 
let cachedSessionFlow: ITestRunModel | undefined;
 
export function sessionFlowRun(): ITestRunModel {
    cachedSessionFlow ??= rawSessionFlow();
    return cachedSessionFlow;
}
 
export function sessionFlowFailure(): ITestRunModel {
    const finished = sessionFlowRun();
    const steps = {...finished.steps};
    const error = {
        message: 'rotated refresh token is missing',
        type: 'login.invalidRefreshToken',
        context: {sessionId: '0198f0c4-6d1a-7a1e-9a52-4b1f0d3f5a01'},
    };
    steps.refreshToken = {
        ...steps.refreshToken,
        status: 'failed',
        endedAt: BASE + 618,
        executionTime: 108,
        duration: 108,
        assertions: {total: 6, threw: 1},
        assertionLog: [
            ...(steps.refreshToken.assertionLog ?? []).slice(0, 5),
            {
                message: 'rotated refresh token is missing',
                passed: false,
                timestamp: BASE + 618,
                source: {
                    file: SOURCE,
                    line: SOURCE_LINES.refreshToken + 8,
                    column: 9,
                    symbol: 'assert',
                },
            },
        ],
        error,
    };
    steps.reuseDetection = {
        ...steps.reuseDetection,
        status: 'failed',
        startedAt: BASE + 619,
        endedAt: BASE + 621,
        executionTime: 2,
        duration: 2,
        assertions: {total: 0, threw: 0},
        assertionLog: undefined,
        error,
    };
    steps.revokedSession = {
        ...steps.revokedSession,
        status: 'failed',
        startedAt: BASE + 622,
        endedAt: BASE + 624,
        executionTime: 2,
        duration: 2,
        assertions: {total: 0, threw: 0},
        assertionLog: undefined,
        error,
    };
    return deriveTestRun({
        ...finished,
        runId: 'run-session-flow-failure',
        status: 'failed',
        steps,
        edges: finished.edges.map(item =>
            item.from === 'refreshToken' || item.from === 'reuseDetection'
                ? {...item, status: 'done'}
                : item,
        ),
    });
}
 
export function sessionFlowRecording(): ITestRunRecording {
    cachedSessionFlowRecording ??= recordingFromRun(sessionFlowRun(), {
        file: SOURCE,
        recordedAt: BASE,
    });
    return cachedSessionFlowRecording;
}
 
let cachedSessionFlowRecording: ITestRunRecording | undefined;
 
let cachedFailureRecording: ITestRunRecording | undefined;
 
export function sessionFlowFailureRecording(): ITestRunRecording {
    cachedFailureRecording ??= recordingFromRun(sessionFlowFailure(), {
        file: SOURCE,
        recordedAt: BASE,
    });
    return cachedFailureRecording;
}
 
/** The same scenario before anything ran, for the Pending story. */
export function sessionFlowPending(): ITestRunModel {
    const finished = sessionFlowRun();
    const steps: Record<string, ITestStepModel> = {};
    for (const name of finished.order) {
        steps[name] = {
            ...finished.steps[name],
            status: 'pending',
            queuedAt: undefined,
            startedAt: undefined,
            endedAt: undefined,
            queueTime: undefined,
            waitTime: undefined,
            executionTime: undefined,
            duration: undefined,
            assertions: {total: 0, threw: 0},
            progress: undefined,
            result: undefined,
            assertionLog: undefined,
            error: undefined,
        };
    }
    return deriveTestRun({
        ...finished,
        runId: 'run-session-flow-pending',
        status: 'pending',
        endedAt: undefined,
        steps,
        edges: [],
        criticalPath: [],
    });
}
 
/** 40 synthetic steps in six groups, for the density story. */
export function denseRun(): ITestRunModel {
    const groups = ['setup', 'auth', 'transfer', 'audit', 'cleanup', 'report'];
    const sizes = [7, 7, 7, 7, 6, 6];
    const steps: Record<string, ITestStepModel> = {};
    const order: string[] = [];
    const edges: ITestEdgeModel[] = [];
    let cursor = 0;
    let previousGroupLast: string | undefined;
    groups.forEach((group, groupIndex) => {
        let previousStep: string | undefined;
        for (let index = 0; index < sizes[groupIndex]; index += 1) {
            const stepName = `${group}Step${index + 1}`;
            const dependsOn =
                previousStep ??
                (groupIndex > 0 && groupIndex % 2 === 1 ? previousGroupLast : undefined);
            const dependencyEnd = dependsOn ? (steps[dependsOn].endedAt ?? BASE) : BASE;
            const start = Math.max(cursor + index * 9, dependencyEnd - BASE + (dependsOn ? 6 : 0));
            const duration = 32 + ((groupIndex * 11 + index * 17) % 180);
            steps[stepName] = step({
                stepName,
                displayName: `${group} ${index + 1}`,
                groupPath: [group],
                startedAt: BASE + start,
                endedAt: BASE + start + duration,
                queueTime: start,
                executionTime: duration,
                duration,
                dependencies: dependsOn ? [dependsOn] : [],
                assertions: {total: 2 + ((groupIndex + index) % 6), threw: 0},
                result: {ok: true},
            });
            order.push(stepName);
            if (dependsOn) edges.push(edge(stepName, dependsOn));
            previousStep = stepName;
            cursor = start + duration + 6;
        }
        previousGroupLast = previousStep;
    });
    const endedAt = Math.max(...Object.values(steps).map(item => item.endedAt ?? BASE));
    return deriveTestRun({
        runId: 'run-dense',
        name: 'dense run',
        method: 'test.dense.flow',
        host: 'browser',
        status: 'completed',
        startedAt: BASE,
        endedAt,
        concurrency: 10,
        order,
        steps,
        edges,
        groups: [],
        counts: {total: 0, pending: 0, running: 0, completed: 0, failed: 0},
        assertions: {total: 0, threw: 0},
        criticalPath: Array.from({length: 7}, (_, index) => `transferStep${index + 1}`),
        logs: [],
        source: {file: 'plans/test-ui/PLAN.md', recordedAt: BASE},
    });
}
 
export function denseRecording(): ITestRunRecording {
    cachedDenseRecording ??= recordingFromRun(denseRun(), {
        file: 'dense fixture',
        recordedAt: BASE,
    });
    return cachedDenseRecording;
}
 
let cachedDenseRecording: ITestRunRecording | undefined;