import { HttpRedaction, SigV4 } from "@effected/crypto"; import type { Redacted, Schema } from "effect"; import { DateTime, Effect, Layer, Option } from "effect"; import { Digest, Mac } from "effect/crypto"; import { HttpClient, HttpClientRequest } from "effect/http"; import type { ActionOutputs } from "./ActionOutputs.js"; import { BlobEnvelope } from "./BlobEnvelope.js"; import type { BlobStoreShape, StoredBlob } from "./BlobStore.js"; import { BlobStore, BlobStoreError } from "./BlobStore.js"; import { Secret } from "./Secret.js"; /** * How to reach an S3-compatible object store. * * @public */ export interface S3Config { /** The bucket name. */ readonly bucket: string; /** The bucket's region, used for SigV4 signing and the default AWS endpoint. */ readonly region: string; /** * A custom endpoint, e.g. `https://.r2.cloudflarestorage.com`. * * @remarks * Omitting it targets AWS itself. Addressing is always **path-style** * (`//`), which is what makes the same layer work * against R2, MinIO and Spaces — virtual-host addressing needs per-bucket * DNS that none of them provide the same way. */ readonly endpoint?: string | undefined; /** The access key id. */ readonly accessKeyId: string; /** The secret access key, declassified once and masked in the runner log. */ readonly secretAccessKey: Redacted.Redacted; /** For temporary credentials. */ readonly sessionToken?: Redacted.Redacted | undefined; /** Prepended to every key, so one bucket can hold several caches. */ readonly prefix?: string | undefined; } const makeS3 = ( config: S3Config, ): Effect.Effect => Effect.gen(function* () { // Trace context stays inside the process: the store is a third party, and // `b3`/`traceparent` would hand it this run's trace and span ids on every // request. The client span is still recorded locally. const http = HttpClient.transform(yield* HttpClient.HttpClient, (effect) => Effect.provideService(effect, HttpClient.TracerPropagationEnabled, false), ); // Resolved once, so every member's `R` stays `never`. const digest = yield* Digest.Digest; const mac = yield* Mac.Mac; // Trailing slashes stripped without a regex: the anchored `/\/+$/` form // backtracks quadratically on slash runs (CodeQL js/polynomial-redos). let endpoint = config.endpoint ?? `https://s3.${config.region}.amazonaws.com`; while (endpoint.endsWith("/")) { endpoint = endpoint.slice(0, -1); } const host = new URL(endpoint).host; // Registered with the runner's log filter ONCE, here, and never // declassified: the signer takes the `Redacted` values and unwraps them // only where it signs, so no plaintext is held by this module. Masking // per request would emit a workflow command per object. yield* Secret.mask(config.secretAccessKey); if (config.sessionToken !== undefined) { yield* Secret.mask(config.sessionToken); } const credentials = { accessKeyId: config.accessKeyId, secretAccessKey: config.secretAccessKey, ...(config.sessionToken === undefined ? {} : { sessionToken: config.sessionToken }), region: config.region, service: "s3", }; const objectPath = (key: string): string => [config.bucket, ...(config.prefix === undefined ? [] : [config.prefix]), key] .join("/") .replaceAll(/\/{2,}/g, "/"); const unsignable = (key: string, cause: unknown): BlobStoreError => new BlobStoreError({ reason: "misconfigured", key, detail: "the request could not be signed", cause }); const request = (method: string, key: string, body: Uint8Array) => Effect.gen(function* () { const path = objectPath(key); // The signing instant comes from `Clock`, so `TestClock` drives it. const now = yield* DateTime.now; const signed = yield* SigV4.sign({ method, path, host, body, now }, credentials).pipe( Effect.provideService(Digest.Digest, digest), Effect.provideService(Mac.Mac, mac), Effect.catchTags({ // A path SigV4 refuses is the caller's key, not the layer's settings. SigV4PathError: (cause) => Effect.fail( new BlobStoreError({ reason: "invalidKey", key, detail: `the path has a "${cause.segment}" segment, which a URL collapses, so it cannot be sent as signed`, cause, }), ), // Text that is not well-formed Unicode: in the path or query it is the // caller's key; in the host, a header or the method it is the layer's settings. SigV4EncodingError: (cause) => Effect.fail( cause.component === "path" || cause.component === "query-key" || cause.component === "query-value" ? new BlobStoreError({ reason: "invalidKey", key, detail: "the key holds a lone UTF-16 surrogate, which cannot be signed", cause, }) : unsignable(key, cause), ), CryptoError: (cause) => Effect.fail(unsignable(key, cause)), }), ); // The URL carries the target exactly as it was signed, never re-encoded: // `!'()*` included, or the store answers SignatureDoesNotMatch. SigV4 // has already refused a `.` or `..` segment, which a URL would collapse. const url = `${endpoint}${signed.path}${signed.query === "" ? "" : `?${signed.query}`}`; return { url, headers: signed.headers }; }); const send = (method: "GET" | "PUT" | "HEAD", key: string, body: Uint8Array) => Effect.gen(function* () { const { url, headers } = yield* request(method, key, body); const base = HttpClientRequest.make(method)(url, { headers }); const built = body.length === 0 ? base : HttpClientRequest.bodyUint8Array(base, body); return yield* http .execute(built) // Every kept cause is redacted: core's error holds the live request, // the SigV4 `authorization` and session token included, as readable fields. .pipe( Effect.mapError( (cause) => new BlobStoreError({ reason: "unreachable", key, cause: HttpRedaction.cause(cause) }), ), ); }); /** Anything outside 2xx is the store refusing; a caller reads `404` first where a miss is an answer. */ const accepted = (key: string, status: number): Effect.Effect => status < 200 || status >= 300 ? Effect.fail(new BlobStoreError({ reason: "refused", key, status })) : Effect.void; return { get: (key: string, schema: Schema.Codec) => Effect.gen(function* () { const response = yield* send("GET", key, new Uint8Array(0)); // A miss is not a failure: it is the answer the caller asked for. if (response.status === 404) { return Option.none>(); } yield* accepted(key, response.status); const buffer = yield* response.arrayBuffer.pipe( Effect.mapError( (cause) => new BlobStoreError({ reason: "unreachable", key, cause: HttpRedaction.cause(cause) }), ), ); return Option.some(yield* Effect.fromResult(BlobEnvelope.decodeResult(new Uint8Array(buffer), schema))); }), put: (key: string, blob: StoredBlob, schema: Schema.Codec) => Effect.gen(function* () { const framed = yield* Effect.fromResult(BlobEnvelope.encodeResult(blob.metadata, blob.body, schema)); const response = yield* send("PUT", key, framed); yield* accepted(key, response.status); }), has: (key: string) => Effect.gen(function* () { const response = yield* send("HEAD", key, new Uint8Array(0)); if (response.status === 404) { return false; } yield* accepted(key, response.status); return true; }), } satisfies BlobStoreShape; }); /** * The S3-compatible {@link BlobStore} backend: AWS S3, Cloudflare R2, MinIO, * DigitalOcean Spaces, anything that speaks S3's object API with SigV4. * * @remarks * The layer lives here rather than as a static on {@link BlobStore} for the * reason `GitHubCacheBlobStore` does: a static belongs to the module that owns * the protocol it needs. A bundler keeps a class's static members with the * class, so the former `BlobStore.layerS3` static put `SigV4` in every bundle that so * much as named the `BlobStore` tag, S3 or not. * * @example * ```ts * import { S3BlobStore } from "@effected/github-actions"; * import { Redacted } from "effect"; * * const layer = S3BlobStore.layer({ * bucket: "my-cache", * region: "auto", * endpoint: "https://.r2.cloudflarestorage.com", * accessKeyId: "key-id", * secretAccessKey: Redacted.make("secret"), * }); * ``` * * @public */ export class S3BlobStore { private constructor() {} /** * An S3-compatible {@link BlobStore} backend, signed with SigV4. * * @remarks * No `@aws-sdk/*` dependency: signing is `@effected/crypto`'s `SigV4`, a * specified algorithm over strings and HMACs. The SDK's weight is in * credential management, retries and a service catalogue none of which this * needs. * * Requires core's `Digest.Digest` and `Mac.Mac` (`effect/crypto`) for the * SHA-256 digests and HMACs signing takes, resolved once when the layer is * built: provide `Digest.layerWebCrypto` and `Mac.layerWebCrypto` (with * `SecureRandom.layerWebCrypto`), or the platform family layers such as * `NodeCrypto.layerDigest` and `NodeCrypto.layerMac`; `NodeServices.layer` * includes neither, and `ActionRuntime.layer` provides both. A request * whose signing fails with core's `CryptoError` fails as * {@link BlobStoreError} `misconfigured`. A * key with a `.` or `..` path segment fails as `invalidKey` before anything * is signed or sent: every URL parser collapses such a segment, so the store * would receive another path than the one signed. * * A parameterized layer factory mints a fresh layer per call and layers * memoize by reference — bind it to a `const` rather than calling it at each * composition site. */ static readonly layer = ( config: S3Config, ): Layer.Layer => Layer.effect(BlobStore, makeS3(config)); }