All files / realm/blong-gateway/server/test/test testMeterFlow.ts

94.41% Statements 321/340
89.47% Branches 17/19
100% Functions 15/15
94.41% Lines 321/340

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 3411x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 1x  
import {type IAssert, type IMeta, handler} from '@feasibleone/blong';
 
/** Decode a JWT payload (base64url) into a plain object. */
function decodeToken(token: string): Record<string, unknown> {
    const payload = token.split('.')[1];
    return JSON.parse(Buffer.from(payload, 'base64url').toString()) as Record<string, unknown>;
}
 
/**
 * The client ids this suite registers, by which its leftovers are recognised.
 *
 * The browser group's two carry a timestamp so that a run's applications are fresh (a
 * fresh crockford id is what makes the metering keys fresh), so they can only be matched
 * as prefixes - the alternative would be a run that cannot clean up after the one before
 * it, which is exactly how these rows came to accumulate.
 */
const REGISTERED_APPLICATION = /^(?:test-app$|http-(?:rate|credit)-)/;
 
/** Extract the `per` claim (base64 permissionMap) from a JWT. */
function decodePermissionMap(token: string): Buffer {
    return Buffer.from(decodeToken(token).per as string, 'base64');
}
 
/**
 * Gateway meter flow — OAuth applications, bundles, subscriptions and the
 * atomic rate/credit metering, plus the uniform (jwt-style) authorization of
 * application tokens via the existing `access.authorization.list`.
 */
export default handler(
    ({
        lib: {group},
        handler: {
            loginTokenCreate,
            gatewayApplicationRegister,
            gatewayBundleMerge,
            gatewaySubscriptionMerge,
            gatewayApplicationRemove,
            gatewaySubscriptionFind,
            gatewaySubscriptionRemove,
            gatewayDropdownList,
            accessAuthorizationList,
            gatewayMeterCheck,
            gatewayCreditAdjust,
            meterLimitReset,
        },
    }) => ({
        testMeterFlow: ({name = 'gateway meter flow'}: {name?: string} = {}) =>
            group(name)([
                // Remove what this suite registered before registering anything else.
                //
                // The tap suite shares its database with the Playwright suite, whose
                // subscription browse capture holds the *seeded* rows - and a registered
                // application is one more active subscription in it. The Playwright backend
                // boots this very group before it runs a spec, so cleaning first is what
                // leaves the capture looking at the seed. Cleaning at the *start* rather
                // than at the end is what a run that fails halfway cannot skip: its rows
                // are removed by the next run either way.
                //
                // The names are the suite's own: this group registers `test-app`, and the
                // browser group (`test.meter.http.flow`) registers an application per run
                // (`http-rate-<timestamp>` / `http-credit-<timestamp>`), which is why two of
                // the three patterns are prefixes. The cleanup lives here rather than in
                // both groups because this is the one that runs wherever the suite runs,
                // and the groups are started in parallel, so two cleanups would race.
                async function cleanupRegistered(assert: IAssert, {$meta}: {$meta: IMeta}) {
                    const lists = await gatewayDropdownList<
                        Record<string, {value: string; label: string}[]>
                    >({}, $meta);
                    const registered = (lists['gateway.application'] ?? []).filter(option =>
                        REGISTERED_APPLICATION.test(option.label),
                    );
                    let subscriptions = 0;
                    for (const application of registered) {
                        // The subscriptions go first: they are the rows a reader sees, and
                        // their foreign key is not cascaded on every path that deletes an
                        // application.
                        const rows = await gatewaySubscriptionFind<{subscriptionId: string}[]>(
                            {filterBy: {applicationId: application.value}},
                            $meta,
                        );
                        for (const row of rows) {
                            await gatewaySubscriptionRemove(
                                {subscriptionId: row.subscriptionId},
                                $meta,
                            );
                            subscriptions += 1;
                        }
                        await gatewayApplicationRemove(
                            {applicationId: application.value},
                            $meta,
                        );
                    }
                    assert.ok(
                        true,
                        `removed ${registered.length} application(s) and ${subscriptions} subscription(s) left by earlier runs`,
                    );
                    return {applications: registered.length, subscriptions};
                },
 
                // Log in as the seeded developer (testUser) to derive the owner id.
                async function loginDeveloper(assert: IAssert, {$meta}: {$meta: IMeta}) {
                    const result = await loginTokenCreate<{
                        token_type: string;
                        access_token: string;
                    }>({username: 'testUser', password: 'testPassword'}, $meta);
                    assert.equal(result.token_type, 'Bearer', 'Developer token type is Bearer');
                    return result;
                },
 
                // Register an OAuth application owned by the developer.
                async function registerApp(
                    assert: IAssert,
                    {
                        $meta,
                        loginDeveloper,
                    }: {$meta: IMeta; loginDeveloper: Awaited<{access_token: string}>},
                ) {
                    const {access_token} = await loginDeveloper;
                    const actorId = String(decodeToken(access_token).sub);
                    const app = await gatewayApplicationRegister<{
                        applicationId: string;
                        clientId: string;
                        clientSecret: string;
                    }>({clientId: 'test-app'}, {...$meta, auth: {actorId}});
                    assert.equal(app.clientId, 'test-app', 'Client id is test-app');
                    assert.ok(app.clientSecret, 'Client secret returned once');
                    return {...app, actorId};
                },
 
                // Reset any leftover metering state for the app (deterministic runs).
                async function resetMeter(
                    assert: IAssert,
                    {
                        $meta,
                        registerApp,
                    }: {$meta: IMeta; registerApp: Awaited<{applicationId: string}>},
                ) {
                    const app = await registerApp;
                    const result = await meterLimitReset<{success: boolean}>(
                        {
                            applicationId: app.applicationId,
                            bundleName: 'Vision AI',
                            clearCredits: true,
                        },
                        $meta,
                    );
                    assert.equal(result.success, true, 'Metering state reset');
                    return app;
                },
 
                // Merge the demo bundles (roles + capabilities + actions).
                async function mergeBundles(assert: IAssert, {$meta}: {$meta: IMeta}) {
                    const result = await gatewayBundleMerge<{success: boolean}>(
                        {
                            bundle: {
                                'Vision AI': {
                                    roleBit: 100,
                                    capability: 'vision',
                                    actions: 'vision.compute',
                                    baseMonthlyCredits: 1000,
                                    rateLimit: 100,
                                    rateWindowSec: 60,
                                    isActive: true,
                                },
                                'Customer API': {
                                    roleBit: 101,
                                    capability: 'customer',
                                    actions: 'customer.get',
                                    baseMonthlyCredits: 500,
                                    rateLimit: 60,
                                    rateWindowSec: 60,
                                    isActive: true,
                                },
                            },
                        },
                        $meta,
                    );
                    assert.equal(result.success, true, 'Bundles merged');
                    return result;
                },
 
                // Subscribe the app to the 'Vision AI' bundle.
                async function subscribeApp(assert: IAssert, {$meta}: {$meta: IMeta}) {
                    const result = await gatewaySubscriptionMerge<{success: boolean}>(
                        {
                            subscription: {
                                testAppVision: {
                                    application: 'test-app',
                                    bundle: 'Vision AI',
                                    status: 'active',
                                    startsAt: '2000-01-01',
                                },
                            },
                        },
                        $meta,
                    );
                    assert.equal(result.success, true, 'Subscription created');
                    return result;
                },
 
                // Mint an OAuth client_credentials token for the application.
                async function appToken(
                    assert: IAssert,
                    {
                        $meta,
                        registerApp,
                    }: {
                        $meta: IMeta;
                        registerApp: Awaited<{clientId: string; clientSecret: string}>;
                    },
                ) {
                    const app = await registerApp;
                    const result = await loginTokenCreate<{
                        token_type: string;
                        access_token: string;
                    }>(
                        {
                            grantType: 'client_credentials',
                            clientId: app.clientId,
                            clientSecret: app.clientSecret,
                        },
                        $meta,
                    );
                    assert.equal(result.token_type, 'Bearer', 'App token type is Bearer');
                    return {...result, app};
                },
 
                // Uniform authorization: access.authorization.list resolves the
                // bundle roleBit baked into the app token.
                async function uniformAuthorization(
                    assert: IAssert,
                    {$meta, appToken}: {$meta: IMeta; appToken: Awaited<{access_token: string}>},
                ) {
                    const {access_token} = await appToken;
                    const permissionMap = decodePermissionMap(access_token);
                    const actions = await accessAuthorizationList<string[]>({permissionMap}, $meta);
                    assert.ok(
                        actions.includes('visionCompute'.toLowerCase()),
                        'App actions include vision.compute (uniform authorization)',
                    );
                    assert.ok(
                        !actions.includes('customerGet'.toLowerCase()),
                        'App actions exclude customer.get (cross-bundle)',
                    );
                    return {actions};
                },
 
                // Meter a vision.compute call (creditCost 5): first request.
                async function meterFirst(
                    assert: IAssert,
                    {
                        $meta,
                        appToken,
                    }: {$meta: IMeta; appToken: Awaited<{app: {applicationId: string}}>},
                ) {
                    const {app} = await appToken;
                    const decision = await gatewayMeterCheck<{
                        allowed: boolean;
                        reason: string;
                        creditsRemaining: number;
                        rateLimit: number;
                    }>(
                        {bundle: 'Vision AI', creditCost: 5},
                        {...$meta, auth: {actorId: app.applicationId}},
                    );
                    assert.equal(decision.allowed, true, 'First metered call allowed');
                    assert.equal(
                        decision.creditsRemaining,
                        1000 - 5,
                        'Credits decremented by creditCost',
                    );
                    assert.ok(decision.rateLimit >= 1, 'Rate limit header data present');
                    return decision;
                },
 
                // Meter again: balance continues to decrease atomically.
                async function meterSecond(
                    assert: IAssert,
                    {
                        $meta,
                        appToken,
                    }: {$meta: IMeta; appToken: Awaited<{app: {applicationId: string}}>},
                ) {
                    const {app} = await appToken;
                    const decision = await gatewayMeterCheck<{
                        allowed: boolean;
                        creditsRemaining: number;
                    }>(
                        {bundle: 'Vision AI', creditCost: 5},
                        {...$meta, auth: {actorId: app.applicationId}},
                    );
                    assert.equal(decision.allowed, true, 'Second metered call allowed');
                    assert.equal(
                        decision.creditsRemaining,
                        1000 - 10,
                        'Credits decremented atomically across calls',
                    );
                    return decision;
                },
 
                // Cross-bundle scope block: app is not subscribed to 'Customer'.
                async function meterCrossBundleBlocked(
                    assert: IAssert,
                    {
                        $meta,
                        appToken,
                    }: {$meta: IMeta; appToken: Awaited<{app: {applicationId: string}}>},
                ) {
                    const {app} = await appToken;
                    const decision = await gatewayMeterCheck<{
                        allowed: boolean;
                        reason: string;
                    }>(
                        {bundle: 'Customer API', creditCost: 1},
                        {...$meta, auth: {actorId: app.applicationId}},
                    );
                    assert.equal(decision.allowed, false, 'Cross-bundle request blocked');
                    assert.equal(decision.reason, 'subscription', 'Block reason is subscription');
                    return decision;
                },
 
                // Mid-month credit scaling via HINCRBY.
                async function adjustCredits(
                    assert: IAssert,
                    {
                        $meta,
                        appToken,
                    }: {$meta: IMeta; appToken: Awaited<{app: {applicationId: string}}>},
                ) {
                    const {app} = await appToken;
                    const result = await gatewayCreditAdjust<{balance: number}>(
                        {applicationId: app.applicationId, delta: 500},
                        $meta,
                    );
                    assert.ok(result.balance >= 500, 'Credits scaled up mid-month');
                    return result;
                },
            ]),
    }),
);