All files / src/internal storage-request.ts

91.01% Statements 81/89
85.05% Branches 74/87
100% Functions 17/17
91.01% Lines 81/89

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277                              5x                                                     5x 5x 5x   5x   5x                                           108x 108x 108x 108x               56x 56x 61x 29x       56x 56x 41x   56x 56x 56x 56x   56x 56x   55x             58x 5x       53x 5x 5x                   5x 5x 5x   5x   5x 5x 5x   5x 3x 3x           3x       3x       3x           2x 2x       2x 2x 2x                     56x 23x 33x   33x       56x 23x                 4x 4x                             14x 10x       4x               1x 1x 1x   1x       4x 4x 5x 5x     4x 4x 4x 4x 4x 4x     4x       15x       4x                 38x 38x           38x       7x 112x   7x    
import { AzureRequestError } from '../azure-request-error'
import { StorageSharedKeyCredential } from '../storage-shared-key-credential'
import {
  getAuthorizationHeader,
  sendWithRetry,
  storageOAuthScope,
  validatedUrl,
} from './request-core'
import type { AzureRequestCredential, RetryOptions } from './request-core'
import { defaultFetch } from './runtime'
import { encodeUtf8 } from './storage-encoding'
import { getAccountNameFromUrl } from './storage-url'
import { parseConnectionString } from './text'
import { requireHttpsUrl } from './url'
 
export const storageServiceVersion = '2024-11-04'
 
export type StorageCredential = AzureRequestCredential | StorageSharedKeyCredential
 
export interface StorageClientOptions {
  fetch?: typeof globalThis.fetch
  retryOptions?: RetryOptions
}
 
export interface StorageRequestInit {
  query?: Partial<Record<string, string>>
  headers?: HeadersInit
  body?: BodyInit
}
 
interface SignableRequest {
  method: string
  url: URL
  headers: Headers
}
 
/** Signing scheme and default headers of a storage service. */
export interface StorageProtocol {
  sign: (request: SignableRequest, credential: StorageSharedKeyCredential) => Promise<string>
  headers: HeadersInit
}
 
const trailingSlash = /\/$/u
const odataVersion = '3.0;NetFx'
const leadingQuestionMark = /^\?/u
 
export const blobProtocol: StorageProtocol = { sign: signBlobRequest, headers: {} }
 
export const tableProtocol: StorageProtocol = {
  sign: signTableRequest,
  headers: {
    // Minimal metadata annotates the property types that JSON cannot express.
    Accept: 'application/json;odata=minimalmetadata',
    DataServiceVersion: odataVersion,
    MaxDataServiceVersion: odataVersion,
  },
}
 
/** Sends authorized Storage REST requests for one client. */
export class StorageTransport {
  private readonly credential: StorageCredential | undefined
  private readonly fetcher: typeof globalThis.fetch
  private readonly retryOptions: RetryOptions | undefined
  private readonly protocol: StorageProtocol
 
  public constructor(
    credential: StorageCredential | undefined,
    options: StorageClientOptions = {},
    protocol: StorageProtocol = blobProtocol,
  ) {
    this.credential = credential
    this.fetcher = options.fetch ?? defaultFetch
    this.retryOptions = options.retryOptions
    this.protocol = protocol
  }
 
  public async send(
    method: string,
    target: string,
    init: StorageRequestInit = {},
  ): Promise<Response> {
    const url = new URL(target)
    for (const [name, value] of Object.entries(init.query ?? {})) {
      if (value !== undefined) {
        url.searchParams.set(name, value)
      }
    }
 
    const headers = new Headers(this.protocol.headers)
    for (const [name, value] of new Headers(init.headers)) {
      headers.set(name, value)
    }
    headers.set('x-ms-date', new Date().toUTCString())
    headers.set('x-ms-version', storageServiceVersion)
    setKnownContentLength(headers, init.body)
    await this.authorize(method, url, headers)
 
    const requestUrl = validatedUrl(url, { method, headers })
    return await sendWithRetry(
      async () =>
        await this.fetcher(requestUrl, { method, headers, body: init.body, redirect: 'manual' }),
      { ...this.retryOptions, body: init.body },
    )
  }
 
  /** Sets the Authorization header when the client has a credential; SAS URLs carry their own. */
  public async authorize(method: string, url: URL, headers: Headers): Promise<void> {
    if (this.credential instanceof StorageSharedKeyCredential) {
      headers.set(
        'Authorization',
        await this.protocol.sign({ method, url, headers }, this.credential),
      )
    } else if (this.credential !== undefined) {
      requireHttpsUrl(url.href, 'Storage request URL')
      headers.set('Authorization', await getAuthorizationHeader(this.credential, storageOAuthScope))
    }
  }
}
 
/** Parses an account key or SAS connection string into a service URL and its credential. */
export function parseStorageConnectionString(
  connectionString: string,
  service: 'blob' | 'table',
): { url: string; credential?: StorageSharedKeyCredential } {
  const parts = parseConnectionString(connectionString)
  const endpointKey = service === 'blob' ? 'BlobEndpoint' : 'TableEndpoint'
  const endpoint = nonEmpty(parts.get(endpointKey)?.replace(trailingSlash, ''))
  const accountName =
    nonEmpty(parts.get('AccountName')) ??
    (endpoint === undefined ? undefined : nonEmpty(getAccountNameFromUrl(endpoint)))
  const accountKey = parts.get('AccountKey')
  const protocol = parts.get('DefaultEndpointsProtocol')?.toLowerCase()
  const accountSas = parts.get('SharedAccessSignature')
 
  if (protocol !== undefined && accountKey !== undefined) {
    const endpointSuffix = nonEmpty(parts.get('EndpointSuffix'))
    Iif (protocol !== 'https' && protocol !== 'http') {
      throw new Error(
        "Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'",
      )
    }
 
    Iif (endpoint === undefined && endpointSuffix === undefined) {
      throw new Error('Invalid EndpointSuffix in the provided Connection String')
    }
 
    Iif (accountName === undefined) {
      throw new Error('Invalid AccountName in the provided Connection String')
    }
 
    return {
      url: endpoint ?? `${protocol}://${accountName}.${service}.${endpointSuffix}`,
      credential: new StorageSharedKeyCredential(accountName, accountKey),
    }
  }
 
  Eif (accountSas !== undefined) {
    Iif (endpoint === undefined) {
      throw new Error(`Invalid ${endpointKey} in the provided SAS Connection String`)
    }
 
    const url = new URL(endpoint)
    url.search = accountSas.replace(leadingQuestionMark, '')
    return { url: url.toString() }
  }
 
  throw new Error(
    'Connection string must be either an Account connection string or a SAS connection string',
  )
}
 
/** Shared key signatures cover Content-Length, so it is set explicitly for bodies of known size. */
function setKnownContentLength(headers: Headers, body: BodyInit | null | undefined): void {
  let length: number | undefined
  if (typeof body === 'string') {
    length = encodeUtf8(body).byteLength
  } else Iif (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {
    length = body.byteLength
  } else Iif (body instanceof Blob) {
    length = body.size
  }
 
  if (length !== undefined) {
    headers.set('Content-Length', String(length))
  }
}
 
/** Shared Key scheme of the Blob service. */
async function signBlobRequest(
  { method, url, headers }: SignableRequest,
  credential: StorageSharedKeyCredential,
): Promise<string> {
  const contentLength = headers.get('Content-Length')
  const stringToSign = [
    method.toUpperCase(),
    headers.get('Content-Encoding') ?? '',
    headers.get('Content-Language') ?? '',
    contentLength === '0' ? '' : (contentLength ?? ''),
    headers.get('Content-MD5') ?? '',
    headers.get('Content-Type') ?? '',
    '',
    headers.get('If-Modified-Since') ?? '',
    headers.get('If-Match') ?? '',
    headers.get('If-None-Match') ?? '',
    headers.get('If-Unmodified-Since') ?? '',
    headers.get('Range') ?? '',
    // Headers iterate with lowercase names in sorted order.
    ...Array.from(headers)
      .filter(([name]) => name.startsWith('x-ms-'))
      .map(([name, value]) => `${name}:${value.trim()}`),
    canonicalizeBlobResource(url, credential.accountName),
  ].join('\n')
 
  return `SharedKey ${credential.accountName}:${await credential.computeHMACSHA256(stringToSign)}`
}
 
/** Shared Key Lite scheme of the Table service. */
async function signTableRequest(
  { url, headers }: SignableRequest,
  credential: StorageSharedKeyCredential,
): Promise<string> {
  const comp = url.searchParams.get('comp')
  const resource = `/${credential.accountName}${url.pathname}${comp === null ? '' : `?comp=${comp}`}`
  const stringToSign = `${headers.get('x-ms-date') ?? ''}\n${resource}`
 
  return `SharedKeyLite ${credential.accountName}:${await credential.computeHMACSHA256(stringToSign)}`
}
 
function canonicalizeBlobResource(url: URL, accountName: string): string {
  const values = new Map<string, string[]>()
  for (const [name, value] of url.searchParams) {
    const key = name.toLowerCase()
    values.set(key, [...(values.get(key) ?? []), value])
  }
 
  const names = [...values.keys()]
  names.sort()
  const parameters = names.map((name) => {
    const sorted = values.get(name) ?? []
    sorted.sort()
    return `${name}:${sorted.join(',')}`
  })
 
  return [`/${accountName}${url.pathname}`, ...parameters].join('\n')
}
 
function nonEmpty(value: string | undefined): string | undefined {
  return value === '' ? undefined : value
}
 
export function storageRequestError(operation: string, response: Response): AzureRequestError {
  return new AzureRequestError(
    `${operation} failed: ${response.status} ${response.statusText}`,
    response.status,
    response.headers.get('x-ms-error-code') ?? undefined,
  )
}
 
/** Account name of a service URL; Shared Key clients need a URL that names the account. */
export function storageAccountName(url: string, credential: StorageCredential | undefined): string {
  const accountName = getAccountNameFromUrl(url)
  Iif (credential instanceof StorageSharedKeyCredential && accountName === '') {
    throw new Error(
      'Unable to extract accountName from provided URL for StorageSharedKeyCredential',
    )
  }
 
  return accountName
}
 
export function multipartBoundary(prefix: string): string {
  const random = Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) =>
    byte.toString(16).padStart(2, '0'),
  )
  return `${prefix}_${random.join('')}`
}