Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

12.3 KB
Raw Blame
import * as Cloudflare from "@/Cloudflare";
import { adopt } from "@/AdoptPolicy";
import { CloudflareEnvironment } from "@/Cloudflare/CloudflareEnvironment";
import * as Provider from "@/Provider";
import * as Test from "@/Test/Alchemy";
import * as vulnScanner from "@distilled.cloud/cloudflare/vulnerability-scanner";
import { expect } from "alchemy-test";
import * as Effect from "effect/Effect";
import * as Redacted from "effect/Redacted";
import { MinimumLogLevel } from "effect/References";
import * as Schedule from "effect/Schedule";

const { test } = Test.make({ providers: Cloudflare.providers() });

const logLevel = Effect.provideService(
  MinimumLogLevel,
  process.env.DEBUG ? "Debug" : "Info",
);

// Deterministic per-test names — same on every run, disjoint between tests.
const SET_DEFAULT = "alchemy-vulnscanner-credset-default";
const SET_CRED = "alchemy-vulnscanner-credset-withcred";
const SET_LIST = "alchemy-vulnscanner-credset-list";
const SET_MOVE_A = "alchemy-vulnscanner-credset-move-a";
const SET_MOVE_B = "alchemy-vulnscanner-credset-move-b";
const CRED_NAME = "alchemy-vulnscanner-credential";
const CRED_MOVE = "alchemy-vulnscanner-credential-move";

const accountIdOf = Effect.gen(function* () {
  const { accountId } = yield* yield* CloudflareEnvironment;
  return accountId;
});

// Freshly minted scoped tokens propagate eventually-consistently across
// Cloudflare's edge; ride out 403 blips on out-of-band verification calls.
const forbiddenRetrySchedule = Schedule.exponential("500 millis");

const getCredentialSet = (accountId: string, credentialSetId: string) =>
  vulnScanner.getCredentialSet({ accountId, credentialSetId }).pipe(
    Effect.retry({
      while: (e) => e._tag === "Forbidden",
      schedule: forbiddenRetrySchedule,
      times: 8,
    }),
  );

// Typed "is it gone?" probes — not-found tags map to undefined.
const findCredentialSet = (accountId: string, credentialSetId: string) =>
  getCredentialSet(accountId, credentialSetId).pipe(
    Effect.catchTag("CredentialSetNotFound", () => Effect.succeed(undefined)),
  );

const getCredential = (
  accountId: string,
  credentialSetId: string,
  credentialId: string,
) =>
  vulnScanner
    .getCredentialSetCredential({ accountId, credentialSetId, credentialId })
    .pipe(
      Effect.retry({
        while: (e) => e._tag === "Forbidden",
        schedule: forbiddenRetrySchedule,
        times: 8,
      }),
    );

const findCredential = (
  accountId: string,
  credentialSetId: string,
  credentialId: string,
) =>
  getCredential(accountId, credentialSetId, credentialId).pipe(
    Effect.catchTag(["CredentialNotFound", "CredentialSetNotFound"], () =>
      Effect.succeed(undefined),
    ),
  );

test.provider("create, rename, and destroy a credential set", (stack) =>
  Effect.gen(function* () {
    const accountId = yield* accountIdOf;

    yield* stack.destroy();

    const initial = yield* stack.deploy(
      Effect.gen(function* () {
        return yield* Cloudflare.VulnerabilityScanner.VulnScannerCredentialSet(
          "DefaultSet",
          {
            name: SET_DEFAULT,
          },
        ).pipe(adopt(true));
      }),
    );

    expect(initial.credentialSetId).toBeDefined();
    expect(initial.accountId).toEqual(accountId);
    expect(initial.name).toEqual(SET_DEFAULT);

    // Out-of-band verification against the live API.
    const live = yield* getCredentialSet(accountId, initial.credentialSetId);
    expect(live.id).toEqual(initial.credentialSetId);
    expect(live.name).toEqual(SET_DEFAULT);

    // Rename in place — same UUID.
    const renamed = yield* stack.deploy(
      Effect.gen(function* () {
        return yield* Cloudflare.VulnerabilityScanner.VulnScannerCredentialSet(
          "DefaultSet",
          {
            name: `${SET_DEFAULT}-renamed`,
          },
        ).pipe(adopt(true));
      }),
    );
    expect(renamed.credentialSetId).toEqual(initial.credentialSetId);
    expect(renamed.name).toEqual(`${SET_DEFAULT}-renamed`);

    const liveRenamed = yield* getCredentialSet(
      accountId,
      renamed.credentialSetId,
    );
    expect(liveRenamed.name).toEqual(`${SET_DEFAULT}-renamed`);

    yield* stack.destroy();

    const gone = yield* findCredentialSet(accountId, initial.credentialSetId);
    expect(gone).toBeUndefined();
  }).pipe(logLevel),
);

test.provider("list enumerates the deployed credential set", (stack) =>
  Effect.gen(function* () {
    yield* stack.destroy();

    const deployed = yield* stack.deploy(
      Effect.gen(function* () {
        return yield* Cloudflare.VulnerabilityScanner.VulnScannerCredentialSet(
          "ListSet",
          {
            name: SET_LIST,
          },
        ).pipe(adopt(true));
      }),
    );

    const provider = yield* Provider.findProvider(
      Cloudflare.VulnerabilityScanner.VulnScannerCredentialSet,
    );
    const all = yield* provider.list();

    // Exhaustively-paginated account collection contains the deployed set,
    // each element shaped exactly like `read`'s Attributes.
    expect(
      all.some((x) => x.credentialSetId === deployed.credentialSetId),
    ).toBe(true);
    const found = all.find(
      (x) => x.credentialSetId === deployed.credentialSetId,
    );
    expect(found?.name).toEqual(SET_LIST);
    expect(found?.accountId).toEqual(deployed.accountId);

    yield* stack.destroy();
  }).pipe(logLevel),
);

test.provider(
  "credential lifecycle — create, mutate in place, rotate value, destroy",
  (stack) =>
    Effect.gen(function* () {
      const accountId = yield* accountIdOf;

      yield* stack.destroy();

      const initial = yield* stack.deploy(
        Effect.gen(function* () {
          const set =
            yield* Cloudflare.VulnerabilityScanner.VulnScannerCredentialSet(
              "CredSet",
              {
                name: SET_CRED,
              },
            ).pipe(adopt(true));
          const credential =
            yield* Cloudflare.VulnerabilityScanner.VulnScannerCredential(
              "Cred",
              {
                credentialSetId: set.credentialSetId,
                name: CRED_NAME,
                location: "header",
                locationName: "authorization",
                value: Redacted.make("Bearer alchemy-test-v1"),
              },
            ).pipe(adopt(true));
          return { set, credential };
        }),
      );

      expect(initial.credential.credentialId).toBeDefined();
      expect(initial.credential.credentialSetId).toEqual(
        initial.set.credentialSetId,
      );
      expect(initial.credential.location).toEqual("header");
      expect(initial.credential.locationName).toEqual("authorization");

      // Out-of-band verification — the value is write-only and never echoed.
      const live = yield* getCredential(
        accountId,
        initial.set.credentialSetId,
        initial.credential.credentialId,
      );
      expect(live.name).toEqual(CRED_NAME);
      expect(live.location).toEqual("header");
      expect(live.locationName).toEqual("authorization");

      // Mutate observable fields + rotate the write-only value in place.
      const updated = yield* stack.deploy(
        Effect.gen(function* () {
          const set =
            yield* Cloudflare.VulnerabilityScanner.VulnScannerCredentialSet(
              "CredSet",
              {
                name: SET_CRED,
              },
            ).pipe(adopt(true));
          const credential =
            yield* Cloudflare.VulnerabilityScanner.VulnScannerCredential(
              "Cred",
              {
                credentialSetId: set.credentialSetId,
                name: CRED_NAME,
                location: "cookie",
                locationName: "session_id",
                value: Redacted.make("alchemy-test-v2"),
              },
            ).pipe(adopt(true));
          return { set, credential };
        }),
      );

      // Same credential updated in place — not a replacement.
      expect(updated.credential.credentialId).toEqual(
        initial.credential.credentialId,
      );
      expect(updated.credential.location).toEqual("cookie");
      expect(updated.credential.locationName).toEqual("session_id");

      const liveUpdated = yield* getCredential(
        accountId,
        updated.set.credentialSetId,
        updated.credential.credentialId,
      );
      expect(liveUpdated.location).toEqual("cookie");
      expect(liveUpdated.locationName).toEqual("session_id");

      yield* stack.destroy();

      const credGone = yield* findCredential(
        accountId,
        initial.set.credentialSetId,
        initial.credential.credentialId,
      );
      expect(credGone).toBeUndefined();
      const setGone = yield* findCredentialSet(
        accountId,
        initial.set.credentialSetId,
      );
      expect(setGone).toBeUndefined();
    }).pipe(logLevel),
);

test.provider(
  "moving a credential to a different set triggers replacement",
  (stack) =>
    Effect.gen(function* () {
      const accountId = yield* accountIdOf;

      yield* stack.destroy();

      // Keep BOTH sets deployed across the replacement step — replacing a
      // resource while removing its old dependency in the same deploy is a
      // known engine deadlock.
      const initial = yield* stack.deploy(
        Effect.gen(function* () {
          const setA =
            yield* Cloudflare.VulnerabilityScanner.VulnScannerCredentialSet(
              "SetA",
              {
                name: SET_MOVE_A,
              },
            ).pipe(adopt(true));
          const setB =
            yield* Cloudflare.VulnerabilityScanner.VulnScannerCredentialSet(
              "SetB",
              {
                name: SET_MOVE_B,
              },
            ).pipe(adopt(true));
          const credential =
            yield* Cloudflare.VulnerabilityScanner.VulnScannerCredential(
              "MovingCred",
              {
                credentialSetId: setA.credentialSetId,
                name: CRED_MOVE,
                location: "header",
                locationName: "x-api-key",
                value: Redacted.make("alchemy-move-v1"),
              },
            ).pipe(adopt(true));
          return { setA, setB, credential };
        }),
      );

      expect(initial.credential.credentialSetId).toEqual(
        initial.setA.credentialSetId,
      );

      const moved = yield* stack.deploy(
        Effect.gen(function* () {
          const setA =
            yield* Cloudflare.VulnerabilityScanner.VulnScannerCredentialSet(
              "SetA",
              {
                name: SET_MOVE_A,
              },
            ).pipe(adopt(true));
          const setB =
            yield* Cloudflare.VulnerabilityScanner.VulnScannerCredentialSet(
              "SetB",
              {
                name: SET_MOVE_B,
              },
            ).pipe(adopt(true));
          const credential =
            yield* Cloudflare.VulnerabilityScanner.VulnScannerCredential(
              "MovingCred",
              {
                credentialSetId: setB.credentialSetId,
                name: CRED_MOVE,
                location: "header",
                locationName: "x-api-key",
                value: Redacted.make("alchemy-move-v1"),
              },
            ).pipe(adopt(true));
          return { setA, setB, credential };
        }),
      );

      // The parent set is the credential's identity — a new physical
      // credential exists under set B.
      expect(moved.credential.credentialSetId).toEqual(
        moved.setB.credentialSetId,
      );
      expect(moved.credential.credentialId).not.toEqual(
        initial.credential.credentialId,
      );

      // The old credential was deleted from set A as part of replacement.
      const oldGone = yield* findCredential(
        accountId,
        initial.setA.credentialSetId,
        initial.credential.credentialId,
      );
      expect(oldGone).toBeUndefined();

      const liveNew = yield* getCredential(
        accountId,
        moved.setB.credentialSetId,
        moved.credential.credentialId,
      );
      expect(liveNew.name).toEqual(CRED_MOVE);

      yield* stack.destroy();

      const setAGone = yield* findCredentialSet(
        accountId,
        initial.setA.credentialSetId,
      );
      expect(setAGone).toBeUndefined();
      const setBGone = yield* findCredentialSet(
        accountId,
        initial.setB.credentialSetId,
      );
      expect(setBGone).toBeUndefined();
    }).pipe(logLevel),
);