All files / src blob-service-client.ts

100% Statements 37/37
77.77% Branches 14/18
100% Functions 12/12
100% Lines 34/34

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                                                                    2x                   31x 31x   31x 31x 31x             3x 3x       22x 22x       3x           1x             5x 1x     4x 1x     3x               5x 5x                           5x 5x 6x   1x 1x       1x             1x             11x 6x 1x     5x   37x   5x 1x     4x    
import { BlobBatchClient } from './blob-batch-client'
import { ContainerClient } from './container-client'
import { listNames } from './internal/blob-listing'
import type { ListOptions } from './internal/paging'
import {
  StorageTransport,
  parseStorageConnectionString,
  storageAccountName,
  storageServiceVersion,
} from './internal/storage-request'
import type { StorageClientOptions, StorageCredential } from './internal/storage-request'
import { appendUrlPath, normalizeStorageUrl } from './internal/storage-url'
import { encodeResourceSegment } from './internal/url'
import { StorageSharedKeyCredential } from './storage-shared-key-credential'
 
export interface ContainerItem {
  name: string
}
 
export interface ListContainersSegment {
  segment: { containerItems: ContainerItem[] }
  continuationToken: string
}
 
export interface AccountSasOptions {
  /** Any of `rwdxftlacupiy`. */
  permissions?: string
  /** Any of `btqf`, defaults to `b`. */
  services?: string
  /** Any of `sco`, defaults to `sco`. */
  resourceTypes?: string
  protocol?: 'https' | 'https,http'
}
 
const fractionalSeconds = /\.\d{3}Z$/u
 
export class BlobServiceClient {
  public readonly accountName: string
  public readonly url: string
  private readonly credential: StorageCredential | undefined
  private readonly options: StorageClientOptions | undefined
  private readonly transport: StorageTransport
 
  public constructor(url: string, credential?: StorageCredential, options?: StorageClientOptions) {
    this.url = normalizeStorageUrl(url)
    this.accountName = storageAccountName(url, credential)
 
    this.credential = credential
    this.options = options
    this.transport = new StorageTransport(credential, options)
  }
 
  public static fromConnectionString(
    connectionString: string,
    options?: StorageClientOptions,
  ): BlobServiceClient {
    const { url, credential } = parseStorageConnectionString(connectionString, 'blob')
    return new BlobServiceClient(url, credential, options)
  }
 
  public getContainerClient(containerName: string): ContainerClient {
    const url = appendUrlPath(this.url, encodeResourceSegment(containerName, 'Container name'))
    return new ContainerClient(url, this.credential, this.options)
  }
 
  public getBlobBatchClient(): BlobBatchClient {
    return new BlobBatchClient(this.url, this.credential, this.options)
  }
 
  public listContainers(): {
    byPage: (options?: ListOptions) => AsyncIterable<ListContainersSegment>
  } {
    return { byPage: (options) => this.listContainerPages(options) }
  }
 
  public async generateAccountSasUrl(
    expiresOn = new Date(Date.now() + 60 * 60 * 1000),
    options: AccountSasOptions = {},
  ): Promise<string> {
    if (!(this.credential instanceof StorageSharedKeyCredential)) {
      throw new TypeError('Account SAS generation requires a StorageSharedKeyCredential')
    }
 
    if (Number.isNaN(expiresOn.getTime())) {
      throw new RangeError('Account SAS expiry must be a valid date')
    }
 
    const parameters = {
      sp: canonicalSasCharacters(options.permissions ?? '', 'rwdxftlacupiy', 'permissions'),
      ss: canonicalSasCharacters(options.services ?? 'b', 'btqf', 'services'),
      srt: canonicalSasCharacters(options.resourceTypes ?? 'sco', 'sco', 'resource types'),
      sv: storageServiceVersion,
      se: expiresOn.toISOString().replace(fractionalSeconds, 'Z'),
      spr: options.protocol ?? 'https',
    }
    const { sp, ss, srt, sv, se, spr } = parameters
    const stringToSign = [
      this.credential.accountName,
      sp,
      ss,
      srt,
      '',
      se,
      '',
      spr,
      sv,
      '',
      '',
    ].join('\n')
 
    const url = new URL(this.url)
    for (const [name, value] of Object.entries(parameters)) {
      url.searchParams.set(name, value)
    }
    url.searchParams.set('sig', await this.credential.computeHMACSHA256(stringToSign))
    return url.toString()
  }
 
  private async *listContainerPages(options?: ListOptions): AsyncGenerator<ListContainersSegment> {
    for await (const { names, continuationToken } of listNames(
      this.transport,
      this.url,
      'Container',
      {},
      options,
    )) {
      yield { segment: { containerItems: names.map((name) => ({ name })) }, continuationToken }
    }
  }
}
 
/** Validates SAS field characters and returns them in the order the service signs them. */
function canonicalSasCharacters(value: string, canonicalOrder: string, field: string): string {
  const invalid = value.split('').find((character) => !canonicalOrder.includes(character))
  if (invalid !== undefined) {
    throw new RangeError(`Invalid Account SAS ${field} character: ${invalid}`)
  }
 
  const canonical = canonicalOrder
    .split('')
    .filter((character) => value.includes(character))
    .join('')
  if (canonical.length === 0) {
    throw new RangeError(`Account SAS ${field} cannot be empty`)
  }
 
  return canonical
}