K6 — проверка подлинности хранилища BLOB-объектов AzureJavascript

Форум по Javascript
Ответить
Anonymous
 K6 — проверка подлинности хранилища BLOB-объектов Azure

Сообщение Anonymous »

Я провожу тестирование производительности с использованием K6, и в рамках тестов мне нужно подключиться и загрузить файл в контейнер BLOB-объектов Azure.
Мой скрипт не проходит проверку подлинности из-за несоответствие заголовков... хотя когда я проверяю, они одинаковы. Я получаю следующий ответ об ошибке:
ERRO[0001] Тело ответа: AuthenticationFailedСерверу не удалось аутентифицировать запрос. Убедитесь, что значение заголовка авторизации сформировано правильно, включая подпись.

RequestId:XXXXXXX

Время:2025-01-10T22:02:41.3196583ZПодпись MAC найдена в HTTP-запрос «xxxxxxx» — это не то же самое, что любая вычисленная подпись. Сервер использовал следующую строку для подписи: 'PUT

Это сценарий K6, который я использую.
Кто-нибудь делал это раньше?

Код: Выделить всё

import {
check
} from 'k6';
import http from 'k6/http';
import encoding from 'k6/encoding';
import crypto from 'k6/crypto';

export const options = {
stages: [{
duration: '1m',
target: 1
},
{
duration: '10m',
target: 1
},
{
duration: '1m',
target: 0
},
],
};

// Environment variables
const storageAccount = __ENV.STORAGE_ACCOUNT;
const containerName = __ENV.CONTAINER_NAME;
const accountKey = __ENV.ACCOUNT_KEY;

if (!storageAccount || !containerName || !accountKey) {
throw new Error("Missing STORAGE_ACCOUNT, CONTAINER_NAME, or ACCESS_KEY environment variables.");
}

// Function to compute HMAC SHA256  signature
function signWithAccountKey(stringToSign, accountKey) {
console.log("Raw Account Key:", accountKey);
const decodedKey = encoding.b64decode(accountKey);
console.log("Decoded Account Key (Hex):", Array.from(decodedKey).map((byte) => byte.toString(16).padStart(2, '0')).join('')); // Log decoded key

const hmac = crypto.createHMAC('sha256', decodedKey);
hmac.update(stringToSign, 'utf8');
const signature = hmac.digest('base64');
console.log("Generated Signature:", signature); // Log the generated signature
return signature;
}

// Function to generate the    Authorization header
function  generateAuthorizationHeader(verb, urlPath, headers) {
const canonicalizedHeaders = Object.keys(headers)
.filter((key) => key.startsWith('x-ms-'))
.sort()
.map((key) => `${key}:${headers[key]}\n`)
.join('');

const canonicalizedResource = `/${storageAccount}${urlPath}`;

const stringToSign = [
verb,
'', // Content-Encoding
'', // Content-Language
headers['Content-Length'] || '', //  Content-Length
'', // Content-MD5
headers['Content-Type'] || '', // Content-Type
'', // Date (not used because we use x-ms-date)
'', // If-Modified-Since
'', // If-Match
'', // If-None-Match
'', // If-Unmodified-Since
'', // Range
canonicalizedHeaders,
canonicalizedResource,
].join('\n');

// Log the StringToSign for debugging
console.log("StringToSign:\n" + stringToSign);

const signature = signWithAccountKey(stringToSign, accountKey);
return `SharedKey ${storageAccount}:${signature}`;
}

// Base URL and content
const baseUrl = `https://${storageAccount}.blob.core.windows.net/${containerName}`;
const fileContent = 'A'.repeat(1024 * 1024 * 100); // Содержимое файла 100 МБ

Код: Выделить всё

export default function() {
const fileName = `test-${__VU}-${__ITER}.xml`;
const urlPath = `/${containerName}/${fileName}`;
const url = `${baseUrl}/${fileName}`;
const date = new Date().toUTCString();

const headers = {
'x-ms-date': date,
'x-ms-version': '2020-10-02',
'x-ms-blob-type': 'BlockBlob',
'Content-Type': 'application/xml',
'Content-Length':  fileContent.length.toString(),
};

headers['Authorization'] =  generateAuthorizationHeader('PUT', urlPath, headers);

// Log headers for debugging
console.log("Authorization Header:", headers['Authorization']);
console.log("Headers Sent:", JSON.stringify(headers));

const res = http.put(url, fileContent,     {
headers
});

const success = check(res, {
'Upload succeeded': (r) => r.status === 201,
});

if (!success) {
console.error(`Upload failed for ${fileName}`);
console.error(`Status: ${res.status}`);
console.error(`Response Body: ${res.body}`);
console.error(`Headers Sent: ${JSON.stringify(headers)}`);
}
}
Спасибо

Подробнее здесь: https://stackoverflow.com/questions/793 ... entication
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»