Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ jobs:
validate:
name: Node.js ${{ matrix.node-version }}
runs-on: ubuntu-latest
env:
CI: "1"
strategy:
fail-fast: false
matrix:
Expand Down
441 changes: 407 additions & 34 deletions .github/workflows/publish.yml

Large diffs are not rendered by default.

8 changes: 5 additions & 3 deletions docs/ADAPTER_AUTHORING.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,11 @@ describe("my adapter", () => {
2. **Conditionals.** Prefer native `If-Match` / `If-None-Match` (or SDK
equivalents). Map precondition failures to `{ ok: false, reason }` — do not
throw for expected races.
3. **Etags.** Opaque strings; pass them through. Never invent etag semantics
components can parse (for example, requiring a quoted form unless every
backend uses it — they do not).
3. **Etags.** Opaque provider-issued strings pass through unchanged. Reject
`"*"` (including surrounding whitespace) for `ifMatch`; the wildcard is
reserved for create-only `ifNoneMatch: "*"`. Never invent other etag
semantics components can parse (for example, requiring a quoted form unless
every backend uses it — they do not).
4. **Streaming.** Accept `ReadableStream` and `Uint8Array`. When the provider
needs multipart under the hood, hide that inside `put`.
5. **Oversize.** Enforce the configured ceiling. Cancelling a remaining body
Expand Down
39 changes: 25 additions & 14 deletions docs/RELEASING.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,24 +40,35 @@ After that pull request is merged, create a signed annotated tag at the exact
create the GitHub release with `--verify-tag`. Do not let GitHub create the tag
and never move or recreate a release tag.

The release workflow verifies that the tag:
Before checking out release source or running repository code, the workflow
authenticates the tag in a fresh bare repository and verifies that it:

- is a stable annotated `vX.Y.Z` tag signed by an allowed signer;
- matches a public package version in the release inventory;
- is a signed annotated tag in the stable package series (`v0.MINOR.PATCH`
with `MINOR >= 1`, or `vMAJOR.MINOR.PATCH` with `MAJOR >= 1`; `v0.0.x` is
not a release tag);
- points to the checkout and the GitHub release-event commit; and
- is contained in `origin/main`.

Its preparation job has no OIDC permission. It enables Corepack for the
reviewed pnpm version, installs the reviewed `npm@11.18.0` used to pack and
talk to the registry, runs the full gate against `pnpm-lock.yaml` without
dependency caching, builds and packs once, smoke-tests the tarball from a
clean consumer, records its SHA-1 and SHA-512 integrity, and uploads the
exact prepared artifact.

Only the `npm-publish` job receives `id-token: write`. It installs no
dependencies and does not download pnpm. It verifies the prepared manifest
and tarball hashes against the release commit, and publishes that tarball
with npm provenance.
Only after those checks does preparation check out the exact release-event
commit and confirm that the tag matches the shared public package version. Its
preparation job has no OIDC permission. It enables Corepack for the reviewed
pnpm version, installs the reviewed `npm@11.18.0`, runs the full gate against
`pnpm-lock.yaml` without dependency caching, removes prior build outputs,
builds and packs once, records SHA-256 and SHA-512 values, enforces an exact
regular-file inventory, and uploads the sealed artifact immediately.

A separate unprivileged smoke job downloads a copy, verifies the manifest
digest recorded by preparation, installs the tarballs in a clean consumer with
package scripts disabled, and imports every exported entry point. Registry
dependencies resolved by that consumer cannot change the artifact used for
publication.

Only the `npm-publish` job receives `id-token: write`. It checks out no source,
installs no dependencies, and does not download pnpm. Workflow-owned logic
re-authenticates the tag in a temporary bare repository, verifies the sealed
manifest and exact artifact inventory, and publishes dependency-ordered
tarballs from fresh temporary working directories with npm provenance and
package scripts disabled.

## Safe retry

Expand Down
39 changes: 39 additions & 0 deletions packages/storage-azure-blob/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,4 +121,43 @@ describe("createAzureBlobStore", () => {
await expect(store.head("some-key")).resolves.toBeNull();
expect(createAttempts).toBe(2);
});

it("rejects a block client outside the configured container", async () => {
const service = serviceClient();
const container = service.getContainerClient(nextContainerName());
const other = service.getContainerClient(nextContainerName());
container.getBlockBlobClient = (key) => other.getBlockBlobClient(key);

const store = createAzureBlobStore({
containerClient: container,
createContainerIfMissing: false,
});

await expect(store.head("some-key")).rejects.toThrow(
"outside the configured container",
);
});

it("rejects encoded dot segments in a block client URL", async () => {
const container = serviceClient().getContainerClient(nextContainerName());
const realClient = container.getBlockBlobClient("some-key");
container.getBlockBlobClient = () =>
new Proxy(realClient, {
get(target, property, receiver) {
if (property === "url") {
return `${container.url}/%2e%2e/other`;
}
return Reflect.get(target, property, receiver);
},
});

const store = createAzureBlobStore({
containerClient: container,
createContainerIfMissing: false,
});

await expect(store.head("some-key")).rejects.toThrow(
"outside the configured container",
);
});
});
149 changes: 61 additions & 88 deletions packages/storage-azure-blob/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,17 @@ import type {
ContainerClient,
} from "@azure/storage-blob";
import {
BlobSizeLimitError,
BlobStoreError,
BlobValidationError,
DEFAULT_CONTENT_TYPE,
DEFAULT_MAX_OBJECT_BYTES,
assertValidEtag,
assertValidBlobKey,
assertValidBlobPrefix,
assertValidCacheControl,
assertValidContentType,
normalizeUserMetadata,
readBlobBody,
type BlobGetResult,
type BlobListPage,
type BlobObjectInfo,
Expand Down Expand Up @@ -95,79 +96,6 @@ function assertMaxBytes(
return maxBytes;
}

function assertEtag(etag: string, label: string): void {
if (typeof etag !== "string" || etag.length === 0) {
throw new BlobValidationError(`${label} must be a non-empty string.`);
}
}

function copyBytes(source: Uint8Array): Uint8Array {
const copy = new Uint8Array(source.byteLength);
copy.set(source);
return copy;
}

async function readBody(
body: ReadableStream<Uint8Array> | Uint8Array,
limitBytes: number,
): Promise<Uint8Array> {
if (body instanceof Uint8Array) {
if (body.byteLength > limitBytes) {
throw new BlobSizeLimitError(limitBytes);
}
return copyBytes(body);
}

const reader = body.getReader();
const chunks: Uint8Array[] = [];
let total = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
if (!(value instanceof Uint8Array)) {
throw new BlobValidationError(
"Body stream chunks must be Uint8Array values.",
);
}
total += value.byteLength;
if (total > limitBytes) {
void reader.cancel().catch(() => {
/* size error wins */
});
throw new BlobSizeLimitError(limitBytes);
}
chunks.push(copyBytes(value));
}
} catch (error) {
if (
error instanceof BlobSizeLimitError ||
error instanceof BlobValidationError
) {
throw error;
}
throw new BlobStoreError("Failed to read object body stream.", {
cause: error,
});
}

if (chunks.length === 0) {
return new Uint8Array(0);
}
if (chunks.length === 1) {
return chunks[0]!;
}
const bytes = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
return bytes;
}

function nodeStreamToWeb(
nodeStream: NodeJS.ReadableStream,
): ReadableStream<Uint8Array> {
Expand Down Expand Up @@ -273,15 +201,21 @@ export function createAzureBlobStore(
const createIfMissing = options.createContainerIfMissing !== false;
const containerName = container.containerName;
// Credential-free identity so SAS query strings never enter list cursors.
let endpoint = container.url;
let containerUrl: URL;
try {
const parsed = new URL(container.url);
parsed.search = "";
parsed.hash = "";
endpoint = parsed.toString();
} catch {
// Fall back to the raw URL if it is not absolute.
containerUrl = new URL(container.url);
} catch (error) {
throw new BlobValidationError("containerClient.url must be absolute.", {
cause: error,
});
}
containerUrl.search = "";
containerUrl.hash = "";
const endpoint = containerUrl.toString();
const containerPathPrefix = `${containerUrl.pathname.replace(/\/$/u, "")}/`;
const decodedContainerPathPrefix = `${decodeURIComponent(
containerUrl.pathname,
).replace(/\/$/u, "")}/`;
const backendId = `${container.accountName ?? "account"}|${endpoint}|${containerName}`;
let ensureContainer: Promise<void> | undefined;

Expand All @@ -303,6 +237,45 @@ export function createAzureBlobStore(
await ensureContainer;
}

function containedBlockBlobClient(key: string) {
Comment thread
FlyOverCoderKY marked this conversation as resolved.
Resolved
const blob = container.getBlockBlobClient(key);
let blobUrl: URL;
try {
blobUrl = new URL(blob.url);
} catch (error) {
throw new BlobStoreError(
`Azure produced an invalid URL for ${JSON.stringify(key)}.`,
{ cause: error },
);
}
let decodedBlobPath: string;
try {
decodedBlobPath = decodeURIComponent(blobUrl.pathname);
} catch (error) {
throw new BlobStoreError(
`Azure produced an invalid URL for ${JSON.stringify(key)}.`,
{ cause: error },
);
}
const relativePath = decodedBlobPath.slice(
decodedContainerPathPrefix.length,
);
if (
blobUrl.origin !== containerUrl.origin ||
!blobUrl.pathname.startsWith(containerPathPrefix) ||
!decodedBlobPath.startsWith(decodedContainerPathPrefix) ||
relativePath.length === 0 ||
relativePath
.split("/")
.some((segment) => segment === "." || segment === "..")
) {
throw new BlobStoreError(
`Azure produced a URL outside the configured container for ${JSON.stringify(key)}.`,
);
}
return blob;
}

return {
async put(key, body, putOptions) {
assertValidBlobKey(key);
Expand All @@ -317,7 +290,7 @@ export function createAzureBlobStore(
throw new BlobValidationError('ifNoneMatch must be the literal "*".');
}
if (ifMatch !== undefined) {
assertEtag(ifMatch, "ifMatch");
assertValidEtag(ifMatch, "ifMatch");
}

const contentType = assertValidContentType(
Expand All @@ -329,10 +302,10 @@ export function createAzureBlobStore(
: assertValidCacheControl(putOptions.cacheControl);
const userMetadata = normalizeUserMetadata(putOptions?.userMetadata);
const limitBytes = assertMaxBytes(putOptions?.maxBytes, maxObjectBytes);
const bytes = await readBody(body, limitBytes);
const bytes = await readBlobBody(body, limitBytes);

await ready();
const blob = container.getBlockBlobClient(key);
const blob = containedBlockBlobClient(key);

const conditions =
ifNoneMatch === "*"
Expand Down Expand Up @@ -409,7 +382,7 @@ export function createAzureBlobStore(
async get(key) {
assertValidBlobKey(key);
await ready();
const blob = container.getBlockBlobClient(key);
const blob = containedBlockBlobClient(key);
let download: BlobDownloadResponseParsed;
try {
download = await blob.download(0);
Expand Down Expand Up @@ -452,7 +425,7 @@ export function createAzureBlobStore(
async head(key) {
assertValidBlobKey(key);
await ready();
const blob = container.getBlockBlobClient(key);
const blob = containedBlockBlobClient(key);
try {
const props = await blob.getProperties();
return toObjectInfo(key, {
Expand All @@ -477,10 +450,10 @@ export function createAzureBlobStore(
assertValidBlobKey(key);
const ifMatch = deleteOptions?.ifMatch;
if (ifMatch !== undefined) {
assertEtag(ifMatch, "ifMatch");
assertValidEtag(ifMatch, "ifMatch");
}
await ready();
const blob = container.getBlockBlobClient(key);
const blob = containedBlockBlobClient(key);
try {
await blob.delete(
ifMatch === undefined ? undefined : { conditions: { ifMatch } },
Expand Down
8 changes: 8 additions & 0 deletions packages/storage-blobs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ Expected races return a result, not an exception:

Infrastructure failures still throw (`BlobStoreError` and subclasses).

### Keys and prefixes

Keys and list prefixes use `/`-delimited segments. A segment equal to `.` or
`..` is rejected; dot-prefixed names such as `.hidden` and `.well-known` remain
valid. A trailing slash is valid for prefixes such as `support-desk/`. To
enumerate every dot-prefixed key, list without a prefix and filter the returned
pages.

### Listing for GC

```ts
Expand Down
Loading
Loading