Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

EnvironmentCredentials.ts

290 lines10.0 KB

1import * as Context from "effect/Context";
2import * as Crypto from "effect/Crypto";
3import * as DateTime from "effect/DateTime";
4import * as Effect from "effect/Effect";
5import * as Encoding from "effect/Encoding";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Schema from "effect/Schema";
9import { and, eq, exists, isNull, ne, notExists } from "drizzle-orm";
10import { QueryBuilder } from "drizzle-orm/pg-core";
11​
12import * as RelayDb from "../db.ts";
13import { relayEnvironmentCredentials, relayEnvironmentLinks } from "../persistence/schema.ts";
14​
15export class EnvironmentCredentialCreatePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialCreatePersistenceError>()(
16 "EnvironmentCredentialCreatePersistenceError",
17 {
18 stage: Schema.Literals([
19 "generate-credential",
20 "hash-token",
21 "insert-credential",
22 "revoke-previous-credentials",
23 ]),
24 environmentId: Schema.String,
25 credentialId: Schema.optionalKey(Schema.String),
26 cause: Schema.Defect(),
27 },
28) {
29 override get message(): string {
30 return `Environment credential creation failed during '${this.stage}' for environment '${this.environmentId}'${this.credentialId === undefined ? "" : `, credential '${this.credentialId}'`}`;
31 }
33​
34export class EnvironmentCredentialAuthenticatePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialAuthenticatePersistenceError>()(
35 "EnvironmentCredentialAuthenticatePersistenceError",
36 {
37 stage: Schema.Literals(["hash-token", "lookup-credential"]),
38 cause: Schema.Defect(),
39 },
40) {
41 override get message(): string {
42 return `Environment credential authentication failed during '${this.stage}'`;
43 }
45​
46export class EnvironmentCredentialRevokePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialRevokePersistenceError>()(
47 "EnvironmentCredentialRevokePersistenceError",
48 {
49 environmentId: Schema.String,
50 cause: Schema.Defect(),
51 },
52) {
53 override get message(): string {
54 return `Failed to revoke credentials for environment '${this.environmentId}'`;
55 }
57​
58export interface EnvironmentCredentialPrincipal {
59 readonly credentialId: string;
60 readonly environmentId: string;
61 readonly environmentPublicKey: string;
63​
64export class EnvironmentCredentials extends Context.Service<
65 EnvironmentCredentials,
66 {
67 readonly create: (input: {
68 readonly environmentId: string;
69 readonly environmentPublicKey: string;
70 }) => Effect.Effect<string, EnvironmentCredentialCreatePersistenceError>;
71 readonly authenticate: (
72 token: string,
73 ) => Effect.Effect<
74 Option.Option<EnvironmentCredentialPrincipal>,
75 EnvironmentCredentialAuthenticatePersistenceError
76 >;
77 readonly revokeForEnvironmentPublicKey: (input: {
78 readonly environmentId: string;
79 readonly environmentPublicKey: string;
80 }) => Effect.Effect<boolean, EnvironmentCredentialRevokePersistenceError>;
81 }
82>()("t3code-relay/environments/EnvironmentCredentials") {}
83​
84const make = Effect.gen(function* () {
85 const db = yield* RelayDb.RelayDb;
86 const crypto = yield* Crypto.Crypto;
87 const hashToken = (token: string) =>
88 crypto
89 .digest("SHA-256", new TextEncoder().encode(token))
90 .pipe(Effect.map(Encoding.encodeBase64Url));
91 const randomTokenPart = (segments: number) =>
92 Effect.map(Effect.all(Array.from({ length: segments }, () => crypto.randomUUIDv4)), (values) =>
93 values.join("").replaceAll("-", ""),
94 );
95 const makeCredential = Effect.fnUntraced(function* () {
96 const credentialId = yield* randomTokenPart(2);
97 const secret = yield* randomTokenPart(3);
98 return {
99 credentialId,
100 token: `t3env_${credentialId}_${secret}`,
101 };
102 });
103​
104 return EnvironmentCredentials.of({
105 create: Effect.fn("relay.environment_credentials.create")(function* (input) {
106 yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
107 const credential = yield* makeCredential().pipe(
108 Effect.mapError(
109 (cause) =>
110 new EnvironmentCredentialCreatePersistenceError({
111 stage: "generate-credential",
112 environmentId: input.environmentId,
113 cause,
114 }),
115 ),
116 );
117 const credentialHash = yield* hashToken(credential.token).pipe(
118 Effect.mapError(
119 (cause) =>
120 new EnvironmentCredentialCreatePersistenceError({
121 stage: "hash-token",
122 environmentId: input.environmentId,
123 credentialId: credential.credentialId,
124 cause,
125 }),
126 ),
127 );
128 const now = DateTime.formatIso(yield* DateTime.now);
129 yield* db
130 .insert(relayEnvironmentCredentials)
131 .values({
132 credentialId: credential.credentialId,
133 environmentId: input.environmentId,
134 environmentPublicKey: input.environmentPublicKey,
135 credentialHash,
136 revokedAt: null,
137 createdAt: now,
138 updatedAt: now,
139 })
140 .pipe(
141 Effect.mapError(
142 (cause) =>
143 new EnvironmentCredentialCreatePersistenceError({
144 stage: "insert-credential",
145 environmentId: input.environmentId,
146 credentialId: credential.credentialId,
147 cause,
148 }),
149 ),
150 );
151 yield* db
152 .update(relayEnvironmentCredentials)
153 .set({
154 revokedAt: now,
155 updatedAt: now,
156 })
157 .where(
158 and(
159 eq(relayEnvironmentCredentials.environmentId, input.environmentId),
160 eq(relayEnvironmentCredentials.environmentPublicKey, input.environmentPublicKey),
161 ne(relayEnvironmentCredentials.credentialId, credential.credentialId),
162 isNull(relayEnvironmentCredentials.revokedAt),
163 ),
164 )
165 .pipe(
166 Effect.mapError(
167 (cause) =>
168 new EnvironmentCredentialCreatePersistenceError({
169 stage: "revoke-previous-credentials",
170 environmentId: input.environmentId,
171 credentialId: credential.credentialId,
172 cause,
173 }),
174 ),
175 );
176 return credential.token;
177 }),
178​
179 authenticate: Effect.fn("relay.environment_credentials.authenticate")(function* (token) {
180 const credentialHash = yield* hashToken(token).pipe(
181 Effect.mapError(
182 (cause) =>
183 new EnvironmentCredentialAuthenticatePersistenceError({
184 stage: "hash-token",
185 cause,
186 }),
187 ),
188 );
189 const rows = yield* db
190 .select({
191 credentialId: relayEnvironmentCredentials.credentialId,
192 environmentId: relayEnvironmentCredentials.environmentId,
193 environmentPublicKey: relayEnvironmentCredentials.environmentPublicKey,
194 })
195 .from(relayEnvironmentCredentials)
196 .where(
197 and(
198 eq(relayEnvironmentCredentials.credentialHash, credentialHash),
199 isNull(relayEnvironmentCredentials.revokedAt),
200 exists(
201 new QueryBuilder()
202 .select({ userId: relayEnvironmentLinks.userId })
203 .from(relayEnvironmentLinks)
204 .where(
205 and(
206 eq(
207 relayEnvironmentLinks.environmentId,
208 relayEnvironmentCredentials.environmentId,
209 ),
210 eq(
211 relayEnvironmentLinks.environmentPublicKey,
212 relayEnvironmentCredentials.environmentPublicKey,
213 ),
214 isNull(relayEnvironmentLinks.revokedAt),
215 ),
216 ),
217 ),
218 ),
219 )
220 .limit(1)
221 .pipe(
222 Effect.mapError(
223 (cause) =>
224 new EnvironmentCredentialAuthenticatePersistenceError({
225 stage: "lookup-credential",
226 cause,
227 }),
228 ),
229 );
230 const row = rows[0];
231 if (row) {
232 yield* Effect.annotateCurrentSpan({ "relay.environment_id": row.environmentId });
233 }
234 return row
235 ? Option.some({
236 credentialId: row.credentialId,
237 environmentId: row.environmentId,
238 environmentPublicKey: row.environmentPublicKey,
239 })
240 : Option.none();
241 }),
242​
243 revokeForEnvironmentPublicKey: Effect.fn(
244 "relay.environment_credentials.revoke_for_environment_public_key",
245 )(function* (input) {
246 yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
247 const revokedAt = DateTime.formatIso(yield* DateTime.now);
248 const rows = yield* db
249 .update(relayEnvironmentCredentials)
250 .set({
251 revokedAt,
252 updatedAt: revokedAt,
253 })
254 .where(
255 and(
256 eq(relayEnvironmentCredentials.environmentId, input.environmentId),
257 eq(relayEnvironmentCredentials.environmentPublicKey, input.environmentPublicKey),
258 isNull(relayEnvironmentCredentials.revokedAt),
259 notExists(
260 new QueryBuilder()
261 .select({ userId: relayEnvironmentLinks.userId })
262 .from(relayEnvironmentLinks)
263 .where(
264 and(
265 eq(relayEnvironmentLinks.environmentId, input.environmentId),
266 eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),
267 isNull(relayEnvironmentLinks.revokedAt),
268 ),
269 ),
270 ),
271 ),
272 )
273 .returning({
274 credentialId: relayEnvironmentCredentials.credentialId,
275 })
276 .pipe(
277 Effect.mapError(
278 (cause) =>
279 new EnvironmentCredentialRevokePersistenceError({
280 environmentId: input.environmentId,
281 cause,
282 }),
283 ),
284 );
285 return rows.length > 0;
286 }),
287 });
288});
289​
290export const layer = Layer.effect(EnvironmentCredentials, make);