Open History to see the last commit
1import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
2import { describe, expect, it } from "@effect/vitest";
3import { PgDialect, QueryBuilder } from "drizzle-orm/pg-core";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6
7import * as RelayDb from "../db.ts";
8import { relayEnvironmentCredentials } from "../persistence/schema.ts";
9import * as EnvironmentCredentials from "./EnvironmentCredentials.ts";
10
11describe("EnvironmentCredentials", () => {
12 it.effect("reports the credential creation persistence stage and preserves its cause", () => {
13 const cause = new Error("database unavailable");
14 const fakeDb = {
15 insert: (table: unknown) => {
16 expect(table).toBe(relayEnvironmentCredentials);
17 return {
18 values: () => Effect.void,
19 };
20 },
21 update: (table: unknown) => {
22 expect(table).toBe(relayEnvironmentCredentials);
23 return {
24 set: () => ({
25 where: () => Effect.fail(cause),
26 }),
27 };
28 },
29 } as unknown as RelayDb.RelayDb["Service"];
30
31 return Effect.gen(function* () {
32 const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;
33 const error = yield* Effect.flip(
34 credentials.create({
35 environmentId: "env_test",
36 environmentPublicKey: "sensitive-public-key-material",
37 }),
38 );
39
40 expect(error).toMatchObject({
41 _tag: "EnvironmentCredentialCreatePersistenceError",
42 stage: "revoke-previous-credentials",
43 environmentId: "env_test",
44 });
45 expect(error.credentialId).toMatch(/^[0-9a-f]{64}$/);
46 expect(error.cause).toBe(cause);
47 expect(error).not.toHaveProperty("environmentPublicKey");
48 }).pipe(
49 Effect.provide(
50 EnvironmentCredentials.layer.pipe(
51 Layer.provide(NodeCryptoLayer.layer),
52 Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)),
53 ),
54 ),
55 );
56 });
57
58 it.effect("does not retain credential tokens when lookup persistence fails", () => {
59 const cause = new Error("database unavailable");
60 const token = "t3env_sensitive-credential-token";
61 const fakeDb = {
62 select: () => ({
63 from: (table: unknown) => {
64 expect(table).toBe(relayEnvironmentCredentials);
65 return {
66 where: () => ({
67 limit: () => Effect.fail(cause),
68 }),
69 };
70 },
71 }),
72 } as unknown as RelayDb.RelayDb["Service"];
73
74 return Effect.gen(function* () {
75 const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;
76 const error = yield* Effect.flip(credentials.authenticate(token));
77
78 expect(error).toMatchObject({
79 _tag: "EnvironmentCredentialAuthenticatePersistenceError",
80 stage: "lookup-credential",
81 });
82 expect(error.cause).toBe(cause);
83 expect(error).not.toHaveProperty("token");
84 }).pipe(
85 Effect.provide(
86 EnvironmentCredentials.layer.pipe(
87 Layer.provide(NodeCryptoLayer.layer),
88 Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)),
89 ),
90 ),
91 );
92 });
93
94 it.effect(
95 "creates opaque credentials and revokes only older credentials for the same key",
96 () => {
97 const insertedValues: Array<{
98 readonly credentialId: string;
99 readonly environmentId: string;
100 readonly environmentPublicKey: string;
101 readonly credentialHash: string;
102 readonly revokedAt: null;
103 readonly createdAt: string;
104 readonly updatedAt: string;
105 }> = [];
106 const staleCredentialRevocations: Array<{
107 readonly values: Record<string, unknown>;
108 readonly condition: unknown;
109 }> = [];
110
111 const fakeDb = {
112 insert: (table: unknown) => {
113 expect(table).toBe(relayEnvironmentCredentials);
114 return {
115 values: (values: (typeof insertedValues)[number]) => {
116 insertedValues.push(values);
117 return Effect.void;
118 },
119 };
120 },
121 update: (table: unknown) => {
122 expect(table).toBe(relayEnvironmentCredentials);
123 return {
124 set: (values: Record<string, unknown>) => ({
125 where: (condition: unknown) => {
126 staleCredentialRevocations.push({ values, condition });
127 return Effect.void;
128 },
129 }),
130 };
131 },
132 } as unknown as RelayDb.RelayDb["Service"];
133
134 return Effect.gen(function* () {
135 const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;
136 const token = yield* credentials.create({
137 environmentId: "env_test",
138 environmentPublicKey: "environment-public-key",
139 });
140 const [, credentialId, secret] = token.split("_");
141
142 expect(token).toMatch(/^t3env_[0-9a-f]{64}_[0-9a-f]{96}$/);
143 expect(credentialId).toHaveLength(64);
144 expect(secret).toHaveLength(96);
145 expect(insertedValues).toHaveLength(1);
146 expect(insertedValues[0]).toMatchObject({
147 credentialId,
148 environmentId: "env_test",
149 environmentPublicKey: "environment-public-key",
150 revokedAt: null,
151 });
152 expect(insertedValues[0]?.credentialHash).toMatch(/^[A-Za-z0-9_-]{43}$/);
153 expect(insertedValues[0]?.credentialHash).not.toContain(token);
154 expect(insertedValues[0]?.createdAt).toBe(insertedValues[0]?.updatedAt);
155 expect(staleCredentialRevocations).toHaveLength(1);
156 expect(staleCredentialRevocations[0]?.values.revokedAt).toEqual(
157 staleCredentialRevocations[0]?.values.updatedAt,
158 );
159
160 const query = new PgDialect().sqlToQuery(staleCredentialRevocations[0]?.condition as never);
161 expect(query.sql).toContain('"relay_environment_credentials"."environment_id" = $1');
162 expect(query.sql).toContain(
163 '"relay_environment_credentials"."environment_public_key" = $2',
164 );
165 expect(query.sql).toContain('"relay_environment_credentials"."credential_id" <> $3');
166 expect(query.sql).toContain('"relay_environment_credentials"."revoked_at" is null');
167 expect(query.params).toEqual(["env_test", "environment-public-key", credentialId]);
168 }).pipe(
169 Effect.provide(
170 EnvironmentCredentials.layer.pipe(
171 Layer.provide(NodeCryptoLayer.layer),
172 Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)),
173 ),
174 ),
175 );
176 },
177 );
178
179 it.effect("revokes active credentials for an environment public key", () => {
180 const updateValues: Array<Record<string, unknown>> = [];
181 const whereConditions: Array<unknown> = [];
182 const fakeDb = {
183 select: (fields: Parameters<QueryBuilder["select"]>[0]) => new QueryBuilder().select(fields),
184 update: (table: unknown) => {
185 expect(table).toBe(relayEnvironmentCredentials);
186 return {
187 set: (values: Record<string, unknown>) => {
188 updateValues.push(values);
189 return {
190 where: (condition: unknown) => {
191 whereConditions.push(condition);
192 return {
193 returning: (selection: unknown) => {
194 expect(selection).toBeDefined();
195 return Effect.succeed([{ credentialId: "credential-1" }]);
196 },
197 };
198 },
199 };
200 },
201 };
202 },
203 } as unknown as RelayDb.RelayDb["Service"];
204
205 return Effect.gen(function* () {
206 const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;
207 const revoked = yield* credentials.revokeForEnvironmentPublicKey({
208 environmentId: "env_test",
209 environmentPublicKey: "environment-public-key",
210 });
211
212 expect(revoked).toBe(true);
213 expect(updateValues).toHaveLength(1);
214 expect(updateValues[0]?.revokedAt).toEqual(updateValues[0]?.updatedAt);
215 expect(whereConditions).toHaveLength(1);
216
217 const query = new PgDialect().sqlToQuery(whereConditions[0] as never);
218 expect(query.sql).toContain('"relay_environment_credentials"."environment_id" = $1');
219 expect(query.sql).toContain('"relay_environment_credentials"."environment_public_key" = $2');
220 expect(query.sql).toContain('"relay_environment_credentials"."revoked_at" is null');
221 expect(query.sql).toContain("not exists");
222 expect(query.sql).toContain('"relay_environment_links"."environment_id" = $3');
223 expect(query.sql).toContain('"relay_environment_links"."environment_public_key" = $4');
224 expect(query.sql).toContain('"relay_environment_links"."revoked_at" is null');
225 expect(query.params).toEqual([
226 "env_test",
227 "environment-public-key",
228 "env_test",
229 "environment-public-key",
230 ]);
231 }).pipe(
232 Effect.provide(
233 EnvironmentCredentials.layer.pipe(
234 Layer.provide(NodeCryptoLayer.layer),
235 Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)),
236 ),
237 ),
238 );
239 });
240});