diff --git a/common/config/rush/pnpm-lock.yaml b/common/config/rush/pnpm-lock.yaml index 6767c3038392..f5ac5c46ab86 100644 --- a/common/config/rush/pnpm-lock.yaml +++ b/common/config/rush/pnpm-lock.yaml @@ -818,6 +818,9 @@ dependencies: '@rush-temp/developer-devcenter': specifier: file:./projects/developer-devcenter.tgz version: file:projects/developer-devcenter.tgz + '@rush-temp/developer-signing': + specifier: file:./projects/developer-signing.tgz + version: file:projects/developer-signing.tgz '@rush-temp/digital-twins-core': specifier: file:./projects/digital-twins-core.tgz version: file:projects/digital-twins-core.tgz @@ -1807,6 +1810,16 @@ packages: lodash: 4.17.21 dev: false + /@microsoft/api-extractor-model@7.28.2(@types/node@14.18.63): + resolution: {integrity: sha512-vkojrM2fo3q4n4oPh4uUZdjJ2DxQ2+RnDQL/xhTWSRUNPF6P4QyrvY357HBxbnltKcYu+nNNolVqc6TIGQ73Ig==} + dependencies: + '@microsoft/tsdoc': 0.14.2 + '@microsoft/tsdoc-config': 0.16.2 + '@rushstack/node-core-library': 3.61.0(@types/node@14.18.63) + transitivePeerDependencies: + - '@types/node' + dev: false + /@microsoft/api-extractor-model@7.28.2(@types/node@16.18.55): resolution: {integrity: sha512-vkojrM2fo3q4n4oPh4uUZdjJ2DxQ2+RnDQL/xhTWSRUNPF6P4QyrvY357HBxbnltKcYu+nNNolVqc6TIGQ73Ig==} dependencies: @@ -1817,6 +1830,26 @@ packages: - '@types/node' dev: false + /@microsoft/api-extractor@7.38.0(@types/node@14.18.63): + resolution: {integrity: sha512-e1LhZYnfw+JEebuY2bzhw0imDCl1nwjSThTrQqBXl40hrVo6xm3j/1EpUr89QyzgjqmAwek2ZkIVZbrhaR+cqg==} + hasBin: true + dependencies: + '@microsoft/api-extractor-model': 7.28.2(@types/node@14.18.63) + '@microsoft/tsdoc': 0.14.2 + '@microsoft/tsdoc-config': 0.16.2 + '@rushstack/node-core-library': 3.61.0(@types/node@14.18.63) + '@rushstack/rig-package': 0.5.1 + '@rushstack/ts-command-line': 4.16.1 + colors: 1.2.5 + lodash: 4.17.21 + resolve: 1.22.6 + semver: 7.5.4 + source-map: 0.6.1 + typescript: 5.0.4 + transitivePeerDependencies: + - '@types/node' + dev: false + /@microsoft/api-extractor@7.38.0(@types/node@16.18.55): resolution: {integrity: sha512-e1LhZYnfw+JEebuY2bzhw0imDCl1nwjSThTrQqBXl40hrVo6xm3j/1EpUr89QyzgjqmAwek2ZkIVZbrhaR+cqg==} hasBin: true @@ -2465,6 +2498,24 @@ packages: rollup: 3.29.4 dev: false + /@rushstack/node-core-library@3.61.0(@types/node@14.18.63): + resolution: {integrity: sha512-tdOjdErme+/YOu4gPed3sFS72GhtWCgNV9oDsHDnoLY5oDfwjKUc9Z+JOZZ37uAxcm/OCahDHfuu2ugqrfWAVQ==} + peerDependencies: + '@types/node': '*' + peerDependenciesMeta: + '@types/node': + optional: true + dependencies: + '@types/node': 14.18.63 + colors: 1.2.5 + fs-extra: 7.0.1 + import-lazy: 4.0.0 + jju: 1.4.0 + resolve: 1.22.6 + semver: 7.5.4 + z-schema: 5.0.5 + dev: false + /@rushstack/node-core-library@3.61.0(@types/node@16.18.55): resolution: {integrity: sha512-tdOjdErme+/YOu4gPed3sFS72GhtWCgNV9oDsHDnoLY5oDfwjKUc9Z+JOZZ37uAxcm/OCahDHfuu2ugqrfWAVQ==} peerDependencies: @@ -4249,7 +4300,7 @@ packages: dependencies: semver: 7.5.4 shelljs: 0.8.5 - typescript: 5.3.0-dev.20231011 + typescript: 5.3.0-dev.20231012 dev: false /eastasianwidth@0.2.0: @@ -8820,6 +8871,37 @@ packages: code-block-writer: 12.0.0 dev: false + /ts-node@10.9.1(@types/node@14.18.63)(typescript@5.0.4): + resolution: {integrity: sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==} + hasBin: true + peerDependencies: + '@swc/core': '>=1.2.50' + '@swc/wasm': '>=1.2.50' + '@types/node': '*' + typescript: '>=2.7' + peerDependenciesMeta: + '@swc/core': + optional: true + '@swc/wasm': + optional: true + dependencies: + '@cspotcode/source-map-support': 0.8.1 + '@tsconfig/node10': 1.0.9 + '@tsconfig/node12': 1.0.11 + '@tsconfig/node14': 1.0.3 + '@tsconfig/node16': 1.0.4 + '@types/node': 14.18.63 + acorn: 8.10.0 + acorn-walk: 8.2.0 + arg: 4.1.3 + create-require: 1.1.1 + diff: 4.0.2 + make-error: 1.3.6 + typescript: 5.0.4 + v8-compile-cache-lib: 3.0.1 + yn: 3.1.1 + dev: false + /ts-node@10.9.1(@types/node@16.18.55)(typescript@5.0.4): resolution: {integrity: sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==} hasBin: true @@ -8993,8 +9075,8 @@ packages: hasBin: true dev: false - /typescript@5.3.0-dev.20231011: - resolution: {integrity: sha512-qpyUI7J37X3Xj7/bPWSNPUvmJ8yDGVnkQ8665xD4+LVWKUX7vwO7n2E1CUuQzeQIF4y369iPaz1d396rTW5LfA==} + /typescript@5.3.0-dev.20231012: + resolution: {integrity: sha512-k/m+QK/2eVsPMAao4I28Cv2Y9WzUKFVhRqvFGZ3CIXc0lrMkw/1pSA+8tp7IMw1ecxoa1myFql1tmCUrMKCbzA==} engines: {node: '>=14.17'} hasBin: true dev: false @@ -17269,7 +17351,7 @@ packages: dev: false file:projects/communication-sms.tgz: - resolution: {integrity: sha512-Zy9WPrxVxDAuq5iLYpiy+HF8IQkHW5qHW8lvszMJ0eKWAWOgTgtr60bcu7A83DWz2vWBXRsGUWKaNqS3yUqOmA==, tarball: file:projects/communication-sms.tgz} + resolution: {integrity: sha512-HPqBjVlUjJug38F2I1GghNK4OH69dfIymbHuB2zKRL+PPuX3EaSSDLRPoJm9FLQke6nSh15tekNMhtT0Mzbr1g==, tarball: file:projects/communication-sms.tgz} name: '@rush-temp/communication-sms' version: 0.0.0 dependencies: @@ -18229,6 +18311,50 @@ packages: - utf-8-validate dev: false + file:projects/developer-signing.tgz: + resolution: {integrity: sha512-xzMppCPzWRkRC0Nk1suFKGaPefxyKAv0+2DgHU1m5dE4T6afC4bRYcVt1LEFBClm+ugp2vHwsVHbMtKokOkKeA==, tarball: file:projects/developer-signing.tgz} + name: '@rush-temp/developer-signing' + version: 0.0.0 + dependencies: + '@azure/identity': 2.1.0 + '@microsoft/api-extractor': 7.38.0(@types/node@14.18.63) + '@types/chai': 4.3.6 + '@types/mocha': 7.0.2 + '@types/node': 14.18.63 + autorest: 3.6.3 + chai: 4.3.10 + cross-env: 7.0.3 + dotenv: 16.3.1 + eslint: 8.50.0 + karma: 6.4.2(debug@4.3.4) + karma-chrome-launcher: 3.2.0 + karma-coverage: 2.2.1 + karma-env-preprocessor: 0.1.1 + karma-firefox-launcher: 2.1.2 + karma-junit-reporter: 2.0.1(karma@6.4.2) + karma-mocha: 2.0.1 + karma-mocha-reporter: 2.2.5(karma@6.4.2) + karma-source-map-support: 1.4.0 + karma-sourcemap-loader: 0.4.0 + mkdirp: 2.1.6 + mocha: 7.2.0 + mocha-junit-reporter: 1.23.3(mocha@7.2.0) + nyc: 15.1.0 + prettier: 2.8.8 + rimraf: 5.0.5 + source-map-support: 0.5.21 + ts-node: 10.9.1(@types/node@14.18.63)(typescript@5.0.4) + tslib: 2.6.2 + typescript: 5.0.4 + transitivePeerDependencies: + - '@swc/core' + - '@swc/wasm' + - bufferutil + - debug + - supports-color + - utf-8-validate + dev: false + file:projects/digital-twins-core.tgz: resolution: {integrity: sha512-dgyqk6KHiJV8rCnQnyz9d+AXXkx3YbDw3W3SM0yD5eXK/WAaVDg+qey2wDzdWGmRMoVjGYfV+7ujfEZ0oKB4xQ==, tarball: file:projects/digital-twins-core.tgz} name: '@rush-temp/digital-twins-core' diff --git a/rush.json b/rush.json index 856393f90efa..058de64cdd91 100644 --- a/rush.json +++ b/rush.json @@ -523,7 +523,9 @@ { "packageName": "@azure/core-http", "projectFolder": "sdk/core/core-http", - "decoupledLocalDependencies": ["@azure/core-tracing"], + "decoupledLocalDependencies": [ + "@azure/core-tracing" + ], "versionPolicyName": "core" }, { @@ -614,7 +616,9 @@ { "packageName": "@azure/identity", "projectFolder": "sdk/identity/identity", - "decoupledLocalDependencies": ["@azure/keyvault-keys"], + "decoupledLocalDependencies": [ + "@azure/keyvault-keys" + ], "versionPolicyName": "client" }, { @@ -2121,6 +2125,11 @@ "packageName": "@azure/arm-playwrighttesting", "projectFolder": "sdk/playwrighttesting/arm-playwrighttesting", "versionPolicyName": "management" + }, + { + "packageName": "@azure-rest/developer-signing", + "projectFolder": "sdk/codesigning/azure-developer-signing-rest", + "versionPolicyName": "client" } ] -} +} \ No newline at end of file diff --git a/sdk/codesigning/azure-developer-signing-rest/.eslintrc.json b/sdk/codesigning/azure-developer-signing-rest/.eslintrc.json new file mode 100644 index 000000000000..619797ac39b6 --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/.eslintrc.json @@ -0,0 +1,11 @@ +{ + "plugins": ["@azure/azure-sdk"], + "extends": ["plugin:@azure/azure-sdk/azure-sdk-base"], + "rules": { + "@azure/azure-sdk/ts-modules-only-named": "warn", + "@azure/azure-sdk/ts-apiextractor-json-types": "warn", + "@azure/azure-sdk/ts-package-json-types": "warn", + "@azure/azure-sdk/ts-package-json-engine-is-present": "warn", + "tsdoc/syntax": "warn" + } +} diff --git a/sdk/codesigning/azure-developer-signing-rest/CHANGELOG.md b/sdk/codesigning/azure-developer-signing-rest/CHANGELOG.md new file mode 100644 index 000000000000..974a0b0afa2b --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/CHANGELOG.md @@ -0,0 +1,3 @@ +## 1.0.0-beta.1 (2023-10-12) + + - Initial Release diff --git a/sdk/codesigning/azure-developer-signing-rest/README.md b/sdk/codesigning/azure-developer-signing-rest/README.md new file mode 100644 index 000000000000..a078a8df924f --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/README.md @@ -0,0 +1,59 @@ +# Azure Signing REST client library for JavaScript + +Azure Developer Signing is a service that provides managed artifact signing for all. + +**Please rely heavily on our [REST client docs](https://github.com/Azure/azure-sdk-for-js/blob/main/documentation/rest-clients.md) to use this library** + +Key links: + +- [Source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/codesigning/azure-developer-signing-rest) +- [Package (NPM)](https://www.npmjs.com/package/@azure-rest/developer-signing) +- [API reference documentation](https://docs.microsoft.com/javascript/api/@azure-rest/developer-signing?view=azure-node-preview) +- [Samples](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/codesigning/azure-developer-signing-rest/samples) + +## Getting started + +### Currently supported environments + +- LTS versions of Node.js + +### Prerequisites + +- You must have an [Azure subscription](https://azure.microsoft.com/free/) to use this package. + +### Install the `@azure-rest/developer-signing` package + +Install the Azure Signing REST client REST client library for JavaScript with `npm`: + +```bash +npm install @azure-rest/developer-signing +``` + +### Create and authenticate a `SigningClient` + +To use an [Azure Active Directory (AAD) token credential](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-with-a-pre-fetched-access-token), +provide an instance of the desired credential type obtained from the +[@azure/identity](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#credentials) library. + +To authenticate with AAD, you must first `npm` install [`@azure/identity`](https://www.npmjs.com/package/@azure/identity) + +After setup, you can choose which type of [credential](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#credentials) from `@azure/identity` to use. +As an example, [DefaultAzureCredential](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#defaultazurecredential) +can be used to authenticate the client. + +Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables: +AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET + +## Troubleshooting + +### Logging + +Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the `AZURE_LOG_LEVEL` environment variable to `info`. Alternatively, logging can be enabled at runtime by calling `setLogLevel` in the `@azure/logger`: + +```javascript +const { setLogLevel } = require("@azure/logger"); + +setLogLevel("info"); +``` + +For more detailed instructions on how to enable logs, you can look at the [@azure/logger package docs](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/logger). diff --git a/sdk/codesigning/azure-developer-signing-rest/api-extractor.json b/sdk/codesigning/azure-developer-signing-rest/api-extractor.json new file mode 100644 index 000000000000..593e7b3cbf4b --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/api-extractor.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "mainEntryPointFilePath": "./types/src/index.d.ts", + "docModel": { + "enabled": true + }, + "apiReport": { + "enabled": true, + "reportFolder": "./review" + }, + "dtsRollup": { + "enabled": true, + "untrimmedFilePath": "", + "publicTrimmedFilePath": "./types/developer-signing.d.ts" + }, + "messages": { + "tsdocMessageReporting": { + "default": { + "logLevel": "none" + } + }, + "extractorMessageReporting": { + "ae-missing-release-tag": { + "logLevel": "none" + }, + "ae-unresolved-link": { + "logLevel": "none" + } + } + } +} \ No newline at end of file diff --git a/sdk/codesigning/azure-developer-signing-rest/karma.conf.js b/sdk/codesigning/azure-developer-signing-rest/karma.conf.js new file mode 100644 index 000000000000..a9d5f1b5fc59 --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/karma.conf.js @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// https://github.com/karma-runner/karma-chrome-launcher +process.env.CHROME_BIN = require("puppeteer").executablePath(); +require("dotenv").config(); +const { relativeRecordingsPath } = require("@azure-tools/test-recorder"); +process.env.RECORDINGS_RELATIVE_PATH = relativeRecordingsPath(); + +module.exports = function (config) { + config.set({ + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: "./", + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ["source-map-support", "mocha"], + + plugins: [ + "karma-mocha", + "karma-mocha-reporter", + "karma-chrome-launcher", + "karma-firefox-launcher", + "karma-env-preprocessor", + "karma-coverage", + "karma-sourcemap-loader", + "karma-junit-reporter", + "karma-source-map-support", + ], + + // list of files / patterns to load in the browser + files: [ + "dist-test/index.browser.js", + { + pattern: "dist-test/index.browser.js.map", + type: "html", + included: false, + served: true, + }, + ], + + // list of files / patterns to exclude + exclude: [], + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + "**/*.js": ["sourcemap", "env"], + // IMPORTANT: COMMENT following line if you want to debug in your browsers!! + // Preprocess source file to calculate code coverage, however this will make source file unreadable + // "dist-test/index.js": ["coverage"] + }, + + envPreprocessor: [ + "TEST_MODE", + "ENDPOINT", + "AZURE_CLIENT_SECRET", + "AZURE_CLIENT_ID", + "AZURE_TENANT_ID", + "SUBSCRIPTION_ID", + "RECORDINGS_RELATIVE_PATH", + ], + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ["mocha", "coverage", "junit"], + + coverageReporter: { + // specify a common output directory + dir: "coverage-browser/", + reporters: [ + { type: "json", subdir: ".", file: "coverage.json" }, + { type: "lcovonly", subdir: ".", file: "lcov.info" }, + { type: "html", subdir: "html" }, + { type: "cobertura", subdir: ".", file: "cobertura-coverage.xml" }, + ], + }, + + junitReporter: { + outputDir: "", // results will be saved as $outputDir/$browserName.xml + outputFile: "test-results.browser.xml", // if included, results will be saved as $outputDir/$browserName/$outputFile + suite: "", // suite will become the package name attribute in xml testsuite element + useBrowserName: false, // add browser name to report and classes names + nameFormatter: undefined, // function (browser, result) to customize the name attribute in xml testcase element + classNameFormatter: undefined, // function (browser, result) to customize the classname attribute in xml testcase element + properties: {}, // key value pair of properties to add to the section of the report + }, + + // web server port + port: 9876, + + // enable / disable colors in the output (reporters and logs) + colors: true, + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: false, + + // --no-sandbox allows our tests to run in Linux without having to change the system. + // --disable-web-security allows us to authenticate from the browser without having to write tests using interactive auth, which would be far more complex. + browsers: ["ChromeHeadlessNoSandbox"], + customLaunchers: { + ChromeHeadlessNoSandbox: { + base: "ChromeHeadless", + flags: ["--no-sandbox", "--disable-web-security"], + }, + }, + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: false, + + // Concurrency level + // how many browser should be started simultaneous + concurrency: 1, + + browserNoActivityTimeout: 60000000, + browserDisconnectTimeout: 10000, + browserDisconnectTolerance: 3, + + client: { + mocha: { + // change Karma's debug.html to the mocha web reporter + reporter: "html", + timeout: "600000", + }, + }, + }); +}; diff --git a/sdk/codesigning/azure-developer-signing-rest/package.json b/sdk/codesigning/azure-developer-signing-rest/package.json new file mode 100644 index 000000000000..165f1db70b9b --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/package.json @@ -0,0 +1,120 @@ +{ + "name": "@azure-rest/developer-signing", + "sdk-type": "client", + "author": "Microsoft Corporation", + "version": "1.0.0-beta.1", + "description": "Azure developer signing service", + "keywords": [ + "node", + "azure", + "cloud", + "typescript", + "browser", + "isomorphic" + ], + "license": "MIT", + "main": "dist/index.js", + "module": "./dist-esm/src/index.js", + "types": "./types/developer-signing.d.ts", + "repository": "github:Azure/azure-sdk-for-js", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "files": [ + "dist/", + "dist-esm/src/", + "types/developer-signing.d.ts", + "README.md", + "LICENSE", + "review/*" + ], + "engines": { + "node": ">=14.0.0" + }, + "scripts": { + "audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit", + "build:browser": "tsc -p . && cross-env ONLY_BROWSER=true rollup -c 2>&1", + "build:node": "tsc -p . && cross-env ONLY_NODE=true rollup -c 2>&1", + "build:samples": "echo skipped.", + "build:test": "tsc -p . && dev-tool run bundle", + "build:debug": "tsc -p . && dev-tool run bundle && api-extractor run --local", + "check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"*.{js,json}\" \"test/**/*.ts\"", + "clean": "rimraf --glob dist dist-browser dist-esm test-dist temp types *.tgz *.log", + "execute:samples": "echo skipped", + "extract-api": "rimraf review && mkdirp ./review && api-extractor run --local", + "format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"*.{js,json}\" \"test/**/*.ts\"", + "generate:client": "echo skipped", + "integration-test:browser": "dev-tool run test:browser", + "integration-test:node": "dev-tool run test:node-js-input -- --timeout 5000000 'dist-esm/test/**/*.spec.js'", + "integration-test": "npm run integration-test:node && npm run integration-test:browser", + "lint:fix": "eslint package.json api-extractor.json src test --ext .ts --fix --fix-type [problem,suggestion]", + "lint": "eslint package.json api-extractor.json src test --ext .ts", + "pack": "npm pack 2>&1", + "test:browser": "npm run clean && npm run build:test && npm run unit-test:browser", + "test:node": "npm run clean && npm run build:test && npm run unit-test:node", + "test": "npm run clean && npm run build:test && npm run unit-test", + "unit-test": "npm run unit-test:node && npm run unit-test:browser", + "unit-test:node": "dev-tool run test:node-ts-input -- --timeout 1200000 --exclude 'test/**/browser/*.spec.ts' 'test/**/*.spec.ts'", + "unit-test:browser": "dev-tool run test:browser", + "build": "npm run clean && tsc -p . && dev-tool run bundle && mkdirp ./review && api-extractor run --local" + }, + "sideEffects": false, + "autoPublish": false, + "dependencies": { + "@azure/core-auth": "^1.3.0", + "@azure-rest/core-client": "^1.1.4", + "@azure/core-rest-pipeline": "^1.12.0", + "@azure/logger": "^1.0.0", + "tslib": "^2.2.0", + "@azure/core-paging": "^1.5.0", + "@azure/core-lro": "^2.5.4", + "@azure/abort-controller": "^1.0.0" + }, + "devDependencies": { + "@microsoft/api-extractor": "^7.31.1", + "autorest": "latest", + "@types/node": "^14.0.0", + "dotenv": "^16.0.0", + "eslint": "^8.0.0", + "mkdirp": "^2.1.2", + "prettier": "^2.5.1", + "rimraf": "^5.0.0", + "source-map-support": "^0.5.9", + "typescript": "~5.0.0", + "@azure/dev-tool": "^1.0.0", + "@azure/eslint-plugin-azure-sdk": "^3.0.0", + "@azure-tools/test-credential": "^1.0.0", + "@azure/identity": "^2.0.1", + "@azure-tools/test-recorder": "^3.0.0", + "mocha": "^7.1.1", + "@types/mocha": "^7.0.2", + "mocha-junit-reporter": "^1.18.0", + "cross-env": "^7.0.2", + "@types/chai": "^4.2.8", + "chai": "^4.2.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-env-preprocessor": "^0.1.1", + "karma-firefox-launcher": "^2.1.2", + "karma-junit-reporter": "^2.0.1", + "karma-mocha-reporter": "^2.2.5", + "karma-mocha": "^2.0.1", + "karma-source-map-support": "~1.4.0", + "karma-sourcemap-loader": "^0.4.0", + "karma": "^6.2.0", + "nyc": "^15.0.0", + "ts-node": "^10.0.0" + }, + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/codesigning/azure-developer-signing-rest/README.md", + "//metadata": { + "constantPaths": [ + { + "path": "src/signingClient.ts", + "prefix": "userAgentInfo" + } + ] + }, + "browser": { + "./dist-esm/test/public/utils/env.js": "./dist-esm/test/public/utils/env.browser.js" + } +} \ No newline at end of file diff --git a/sdk/codesigning/azure-developer-signing-rest/review/developer-signing.api.md b/sdk/codesigning/azure-developer-signing-rest/review/developer-signing.api.md new file mode 100644 index 000000000000..ed7f889476d6 --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/review/developer-signing.api.md @@ -0,0 +1,263 @@ +## API Report File for "@azure-rest/developer-signing" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { Client } from '@azure-rest/core-client'; +import { ClientOptions } from '@azure-rest/core-client'; +import { CreateHttpPollerOptions } from '@azure/core-lro'; +import { ErrorModel } from '@azure-rest/core-client'; +import { ErrorResponse } from '@azure-rest/core-client'; +import { HttpResponse } from '@azure-rest/core-client'; +import { OperationState } from '@azure/core-lro'; +import { Paged } from '@azure/core-paging'; +import { PagedAsyncIterableIterator } from '@azure/core-paging'; +import { PathUncheckedResponse } from '@azure-rest/core-client'; +import { RawHttpHeaders } from '@azure/core-rest-pipeline'; +import { RequestParameters } from '@azure-rest/core-client'; +import { SimplePollerLike } from '@azure/core-lro'; +import { StreamableMethod } from '@azure-rest/core-client'; +import { TokenCredential } from '@azure/core-auth'; + +// @public +function createClient(region: string, credentials: TokenCredential, options?: ClientOptions): SigningClient; +export default createClient; + +// @public +export interface ExtendedKeyUsageOutput { + readonly eku: string; +} + +// @public +export type GetArrayType = T extends Array ? TData : never; + +// @public +export function getLongRunningPoller(client: Client, initialResponse: Sign202Response | SignDefaultResponse, options?: CreateHttpPollerOptions>): Promise, TResult>>; + +// @public +export type GetPage = (pageLink: string, maxPageSize?: number) => Promise<{ + page: TPage; + nextPageLink?: string; +}>; + +// @public (undocumented) +export interface GetSigningStatus { + get(options?: GetSigningStatusParameters): StreamableMethod; +} + +// @public +export interface GetSigningStatus200Response extends HttpResponse { + // (undocumented) + body: OperationStatusOutput; + // (undocumented) + status: "200"; +} + +// @public (undocumented) +export interface GetSigningStatusDefaultHeaders { + "x-ms-error-code"?: string; +} + +// @public (undocumented) +export interface GetSigningStatusDefaultResponse extends HttpResponse { + // (undocumented) + body: ErrorResponse; + // (undocumented) + headers: RawHttpHeaders & GetSigningStatusDefaultHeaders; + // (undocumented) + status: string; +} + +// @public (undocumented) +export type GetSigningStatusParameters = RequestParameters; + +// @public (undocumented) +export interface GetSignRootCertificate { + get(options?: GetSignRootCertificateParameters): StreamableMethod; +} + +// @public +export interface GetSignRootCertificate200Response extends HttpResponse { + body: Uint8Array; + // (undocumented) + status: "200"; +} + +// @public (undocumented) +export interface GetSignRootCertificateDefaultHeaders { + "x-ms-error-code"?: string; +} + +// @public (undocumented) +export interface GetSignRootCertificateDefaultResponse extends HttpResponse { + // (undocumented) + body: ErrorResponse; + // (undocumented) + headers: RawHttpHeaders & GetSignRootCertificateDefaultHeaders; + // (undocumented) + status: string; +} + +// @public (undocumented) +export type GetSignRootCertificateParameters = RequestParameters; + +// @public (undocumented) +export function isUnexpected(response: GetSigningStatus200Response | GetSigningStatusDefaultResponse): response is GetSigningStatusDefaultResponse; + +// @public (undocumented) +export function isUnexpected(response: GetSignRootCertificate200Response | GetSignRootCertificateDefaultResponse): response is GetSignRootCertificateDefaultResponse; + +// @public (undocumented) +export function isUnexpected(response: ListExtendedKeyUsages200Response | ListExtendedKeyUsagesDefaultResponse): response is ListExtendedKeyUsagesDefaultResponse; + +// @public (undocumented) +export function isUnexpected(response: Sign202Response | SignLogicalResponse | SignDefaultResponse): response is SignDefaultResponse; + +// @public (undocumented) +export interface ListExtendedKeyUsages { + get(options?: ListExtendedKeyUsagesParameters): StreamableMethod; +} + +// @public +export interface ListExtendedKeyUsages200Response extends HttpResponse { + // (undocumented) + body: PagedExtendedKeyUsageOutput; + // (undocumented) + status: "200"; +} + +// @public (undocumented) +export interface ListExtendedKeyUsagesDefaultHeaders { + "x-ms-error-code"?: string; +} + +// @public (undocumented) +export interface ListExtendedKeyUsagesDefaultResponse extends HttpResponse { + // (undocumented) + body: ErrorResponse; + // (undocumented) + headers: RawHttpHeaders & ListExtendedKeyUsagesDefaultHeaders; + // (undocumented) + status: string; +} + +// @public (undocumented) +export type ListExtendedKeyUsagesParameters = RequestParameters; + +// @public +export interface OperationStatusOutput { + error?: ErrorModel; + id: string; + result?: SignResultOutput; + status: string; +} + +// @public +export type PagedExtendedKeyUsageOutput = Paged; + +// @public +export function paginate(client: Client, initialResponse: TResponse, options?: PagingOptions): PagedAsyncIterableIterator>; + +// @public +export type PaginateReturn = TResult extends { + body: { + value?: infer TPage; + }; +} ? GetArrayType : Array; + +// @public +export interface PagingOptions { + customGetPage?: GetPage[]>; +} + +// @public +export interface ResourceOperationStatusOutput { + error?: ErrorModel; + id: string; + result?: SignResultOutput; + status: string; +} + +// @public (undocumented) +export interface Routes { + (path: "/codesigningaccounts/{accountName}/certificateprofiles/{certificateProfile}/sign/{operationId}", operationId: string, accountName: string, certificateProfile: string): GetSigningStatus; + (path: "/codesigningaccounts/{accountName}/certificateprofiles/{certificateProfile}/sign/rootcert", accountName: string, certificateProfile: string): GetSignRootCertificate; + (path: "/codesigningaccounts/{accountName}/certificateprofiles/{certificateProfile}/sign/eku", accountName: string, certificateProfile: string): ListExtendedKeyUsages; + (path: "/codesigningaccounts/{accountName}/certificateprofiles/{certificateProfile}:sign", accountName: string, certificateProfile: string): Sign; +} + +// @public (undocumented) +export interface Sign { + post(options?: SignParameters): StreamableMethod; +} + +// @public (undocumented) +export interface Sign202Headers { + "operation-location": string; +} + +// @public +export interface Sign202Response extends HttpResponse { + // (undocumented) + body: ResourceOperationStatusOutput; + // (undocumented) + headers: RawHttpHeaders & Sign202Headers; + // (undocumented) + status: "202"; +} + +// @public (undocumented) +export interface SignBodyParam { + // (undocumented) + body?: SigningPayloadOptions; +} + +// @public (undocumented) +export interface SignDefaultHeaders { + "x-ms-error-code"?: string; +} + +// @public (undocumented) +export interface SignDefaultResponse extends HttpResponse { + // (undocumented) + body: ErrorResponse; + // (undocumented) + headers: RawHttpHeaders & SignDefaultHeaders; + // (undocumented) + status: string; +} + +// @public (undocumented) +export type SigningClient = Client & { + path: Routes; +}; + +// @public +export interface SigningPayloadOptions { + authenticodeHashList?: string[]; + digest: string; + fileHashList?: string[]; + signatureAlgorithm: string; +} + +// @public +export interface SignLogicalResponse extends HttpResponse { + // (undocumented) + body: ResourceOperationStatusOutput; + // (undocumented) + status: "200"; +} + +// @public (undocumented) +export type SignParameters = SignBodyParam & RequestParameters; + +// @public +export interface SignResultOutput { + signature?: string; + signingCertificate?: string; +} + +// (No @packageDocumentation comment for this package) + +``` diff --git a/sdk/codesigning/azure-developer-signing-rest/src/clientDefinitions.ts b/sdk/codesigning/azure-developer-signing-rest/src/clientDefinitions.ts new file mode 100644 index 000000000000..d06114181093 --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/src/clientDefinitions.ts @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + GetSigningStatusParameters, + GetSignRootCertificateParameters, + ListExtendedKeyUsagesParameters, + SignParameters, +} from "./parameters"; +import { + GetSigningStatus200Response, + GetSigningStatusDefaultResponse, + GetSignRootCertificate200Response, + GetSignRootCertificateDefaultResponse, + ListExtendedKeyUsages200Response, + ListExtendedKeyUsagesDefaultResponse, + Sign202Response, + SignDefaultResponse, +} from "./responses"; +import { Client, StreamableMethod } from "@azure-rest/core-client"; + +export interface GetSigningStatus { + /** This status operation requires that a Sign request has been submitted and the operationId is known. */ + get( + options?: GetSigningStatusParameters + ): StreamableMethod< + GetSigningStatus200Response | GetSigningStatusDefaultResponse + >; +} + +export interface GetSignRootCertificate { + /** The root certificate is generated as part of the initial account creation and it is used to sign the bits for the profile provided. */ + get( + options?: GetSignRootCertificateParameters + ): StreamableMethod< + GetSignRootCertificate200Response | GetSignRootCertificateDefaultResponse + >; +} + +export interface ListExtendedKeyUsages { + /** The list of extended key usages are used to determine the purpose of the certificate usage as part of the signing operation. */ + get( + options?: ListExtendedKeyUsagesParameters + ): StreamableMethod< + ListExtendedKeyUsages200Response | ListExtendedKeyUsagesDefaultResponse + >; +} + +export interface Sign { + /** Submit a sign operation under the created account and profile name provided. */ + post( + options?: SignParameters + ): StreamableMethod; +} + +export interface Routes { + /** Resource for '/codesigningaccounts/\{accountName\}/certificateprofiles/\{certificateProfile\}/sign/\{operationId\}' has methods for the following verbs: get */ + ( + path: "/codesigningaccounts/{accountName}/certificateprofiles/{certificateProfile}/sign/{operationId}", + operationId: string, + accountName: string, + certificateProfile: string + ): GetSigningStatus; + /** Resource for '/codesigningaccounts/\{accountName\}/certificateprofiles/\{certificateProfile\}/sign/rootcert' has methods for the following verbs: get */ + ( + path: "/codesigningaccounts/{accountName}/certificateprofiles/{certificateProfile}/sign/rootcert", + accountName: string, + certificateProfile: string + ): GetSignRootCertificate; + /** Resource for '/codesigningaccounts/\{accountName\}/certificateprofiles/\{certificateProfile\}/sign/eku' has methods for the following verbs: get */ + ( + path: "/codesigningaccounts/{accountName}/certificateprofiles/{certificateProfile}/sign/eku", + accountName: string, + certificateProfile: string + ): ListExtendedKeyUsages; + /** Resource for '/codesigningaccounts/\{accountName\}/certificateprofiles/\{certificateProfile\}:sign' has methods for the following verbs: post */ + ( + path: "/codesigningaccounts/{accountName}/certificateprofiles/{certificateProfile}:sign", + accountName: string, + certificateProfile: string + ): Sign; +} + +export type SigningClient = Client & { + path: Routes; +}; diff --git a/sdk/codesigning/azure-developer-signing-rest/src/index.ts b/sdk/codesigning/azure-developer-signing-rest/src/index.ts new file mode 100644 index 000000000000..50cb0c3465b4 --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/src/index.ts @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import SigningClient from "./signingClient"; + +export * from "./signingClient"; +export * from "./parameters"; +export * from "./responses"; +export * from "./clientDefinitions"; +export * from "./isUnexpected"; +export * from "./models"; +export * from "./outputModels"; +export * from "./paginateHelper"; +export * from "./pollingHelper"; + +export default SigningClient; diff --git a/sdk/codesigning/azure-developer-signing-rest/src/isUnexpected.ts b/sdk/codesigning/azure-developer-signing-rest/src/isUnexpected.ts new file mode 100644 index 000000000000..9be3b3adf68b --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/src/isUnexpected.ts @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + GetSigningStatus200Response, + GetSigningStatusDefaultResponse, + GetSignRootCertificate200Response, + GetSignRootCertificateDefaultResponse, + ListExtendedKeyUsages200Response, + ListExtendedKeyUsagesDefaultResponse, + Sign202Response, + SignLogicalResponse, + SignDefaultResponse, +} from "./responses"; + +const responseMap: Record = { + "GET /codesigningaccounts/{accountName}/certificateprofiles/{certificateProfile}/sign/{operationId}": + ["200"], + "GET /codesigningaccounts/{accountName}/certificateprofiles/{certificateProfile}/sign/rootcert": + ["200"], + "GET /codesigningaccounts/{accountName}/certificateprofiles/{certificateProfile}/sign/eku": + ["200"], + "POST /codesigningaccounts/{accountName}/certificateprofiles/{certificateProfile}:sign": + ["202"], + "GET /codesigningaccounts/{accountName}/certificateprofiles/{certificateProfile}:sign": + ["200", "202"], +}; + +export function isUnexpected( + response: GetSigningStatus200Response | GetSigningStatusDefaultResponse +): response is GetSigningStatusDefaultResponse; +export function isUnexpected( + response: + | GetSignRootCertificate200Response + | GetSignRootCertificateDefaultResponse +): response is GetSignRootCertificateDefaultResponse; +export function isUnexpected( + response: + | ListExtendedKeyUsages200Response + | ListExtendedKeyUsagesDefaultResponse +): response is ListExtendedKeyUsagesDefaultResponse; +export function isUnexpected( + response: Sign202Response | SignLogicalResponse | SignDefaultResponse +): response is SignDefaultResponse; +export function isUnexpected( + response: + | GetSigningStatus200Response + | GetSigningStatusDefaultResponse + | GetSignRootCertificate200Response + | GetSignRootCertificateDefaultResponse + | ListExtendedKeyUsages200Response + | ListExtendedKeyUsagesDefaultResponse + | Sign202Response + | SignLogicalResponse + | SignDefaultResponse +): response is + | GetSigningStatusDefaultResponse + | GetSignRootCertificateDefaultResponse + | ListExtendedKeyUsagesDefaultResponse + | SignDefaultResponse { + const lroOriginal = response.headers["x-ms-original-url"]; + const url = new URL(lroOriginal ?? response.request.url); + const method = response.request.method; + let pathDetails = responseMap[`${method} ${url.pathname}`]; + if (!pathDetails) { + pathDetails = getParametrizedPathSuccess(method, url.pathname); + } + return !pathDetails.includes(response.status); +} + +function getParametrizedPathSuccess(method: string, path: string): string[] { + const pathParts = path.split("/"); + + // Traverse list to match the longest candidate + // matchedLen: the length of candidate path + // matchedValue: the matched status code array + let matchedLen = -1, + matchedValue: string[] = []; + + // Iterate the responseMap to find a match + for (const [key, value] of Object.entries(responseMap)) { + // Extracting the path from the map key which is in format + // GET /path/foo + if (!key.startsWith(method)) { + continue; + } + const candidatePath = getPathFromMapKey(key); + // Get each part of the url path + const candidateParts = candidatePath.split("/"); + + // track if we have found a match to return the values found. + let found = true; + for ( + let i = candidateParts.length - 1, j = pathParts.length - 1; + i >= 1 && j >= 1; + i--, j-- + ) { + if ( + candidateParts[i]?.startsWith("{") && + candidateParts[i]?.indexOf("}") !== -1 + ) { + const start = candidateParts[i]!.indexOf("}") + 1, + end = candidateParts[i]?.length; + // If the current part of the candidate is a "template" part + // Try to use the suffix of pattern to match the path + // {guid} ==> $ + // {guid}:export ==> :export$ + const isMatched = new RegExp( + `${candidateParts[i]?.slice(start, end)}` + ).test(pathParts[j] || ""); + + if (!isMatched) { + found = false; + break; + } + continue; + } + + // If the candidate part is not a template and + // the parts don't match mark the candidate as not found + // to move on with the next candidate path. + if (candidateParts[i] !== pathParts[j]) { + found = false; + break; + } + } + + // We finished evaluating the current candidate parts + // Update the matched value if and only if we found the longer pattern + if (found && candidatePath.length > matchedLen) { + matchedLen = candidatePath.length; + matchedValue = value; + } + } + + return matchedValue; +} + +function getPathFromMapKey(mapKey: string): string { + const pathStart = mapKey.indexOf("/"); + return mapKey.slice(pathStart); +} diff --git a/sdk/codesigning/azure-developer-signing-rest/src/logger.ts b/sdk/codesigning/azure-developer-signing-rest/src/logger.ts new file mode 100644 index 000000000000..274f3caeedab --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/src/logger.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { createClientLogger } from "@azure/logger"; +export const logger = createClientLogger("developer-signing"); diff --git a/sdk/codesigning/azure-developer-signing-rest/src/models.ts b/sdk/codesigning/azure-developer-signing-rest/src/models.ts new file mode 100644 index 000000000000..7c7394fb8b1a --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/src/models.ts @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/** The artifact request information to be signed by the service. */ +export interface SigningPayloadOptions { + /** + * The supported signature algorithm identifiers. + * + * Possible values: RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, ES512, ES256K + */ + signatureAlgorithm: string; + /** Content digest to sign. */ + digest: string; + /** List of full file digital signatures. */ + fileHashList?: string[]; + /** List of authenticode digital signatures. */ + authenticodeHashList?: string[]; +} diff --git a/sdk/codesigning/azure-developer-signing-rest/src/outputModels.ts b/sdk/codesigning/azure-developer-signing-rest/src/outputModels.ts new file mode 100644 index 000000000000..3d5ebadd3363 --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/src/outputModels.ts @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { Paged } from "@azure/core-paging"; +import { ErrorModel } from "@azure-rest/core-client"; + +/** The sign status model. */ +export interface SignResultOutput { + /** Digital signature of the requested content digest. */ + signature?: string; + /** + * Signing certificate corresponding to the private key used to sign the requested + * digest. + */ + signingCertificate?: string; +} + +/** Provides status details for long running operations. */ +export interface OperationStatusOutput { + /** The unique ID of the operation. */ + id: string; + /** + * The status of the operation + * + * Possible values: InProgress, Succeeded, Failed, Canceled + */ + status: string; + /** Error object that describes the error when status is "Failed". */ + error?: ErrorModel; + /** The result of the operation. */ + result?: SignResultOutput; +} + +/** Extended key usage object identifier that are allowable. */ +export interface ExtendedKeyUsageOutput { + /** An oid string that represents an eku. */ + readonly eku: string; +} + +/** Provides status details for long running operations. */ +export interface ResourceOperationStatusOutput { + /** The unique ID of the operation. */ + id: string; + /** + * The status of the operation + * + * Possible values: InProgress, Succeeded, Failed, Canceled + */ + status: string; + /** Error object that describes the error when status is "Failed". */ + error?: ErrorModel; + /** The result of the operation. */ + result?: SignResultOutput; +} + +/** Paged collection of ExtendedKeyUsage items */ +export type PagedExtendedKeyUsageOutput = Paged; diff --git a/sdk/codesigning/azure-developer-signing-rest/src/paginateHelper.ts b/sdk/codesigning/azure-developer-signing-rest/src/paginateHelper.ts new file mode 100644 index 000000000000..1c9af35b1efd --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/src/paginateHelper.ts @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + getPagedAsyncIterator, + PagedAsyncIterableIterator, + PagedResult, +} from "@azure/core-paging"; +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; + +/** + * Helper type to extract the type of an array + */ +export type GetArrayType = T extends Array ? TData : never; + +/** + * The type of a custom function that defines how to get a page and a link to the next one if any. + */ +export type GetPage = ( + pageLink: string, + maxPageSize?: number +) => Promise<{ + page: TPage; + nextPageLink?: string; +}>; + +/** + * Options for the paging helper + */ +export interface PagingOptions { + /** + * Custom function to extract pagination details for crating the PagedAsyncIterableIterator + */ + customGetPage?: GetPage[]>; +} + +/** + * Helper type to infer the Type of the paged elements from the response type + * This type is generated based on the swagger information for x-ms-pageable + * specifically on the itemName property which indicates the property of the response + * where the page items are found. The default value is `value`. + * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter + */ +export type PaginateReturn = TResult extends { + body: { value?: infer TPage }; +} + ? GetArrayType + : Array; + +/** + * Helper to paginate results from an initial response that follows the specification of Autorest `x-ms-pageable` extension + * @param client - Client to use for sending the next page requests + * @param initialResponse - Initial response containing the nextLink and current page of elements + * @param customGetPage - Optional - Function to define how to extract the page and next link to be used to paginate the results + * @returns - PagedAsyncIterableIterator to iterate the elements + */ +export function paginate( + client: Client, + initialResponse: TResponse, + options: PagingOptions = {} +): PagedAsyncIterableIterator> { + // Extract element type from initial response + type TElement = PaginateReturn; + let firstRun = true; + const itemName = "value"; + const nextLinkName = "nextLink"; + const { customGetPage } = options; + const pagedResult: PagedResult = { + firstPageLink: "", + getPage: + typeof customGetPage === "function" + ? customGetPage + : async (pageLink: string) => { + const result = firstRun + ? initialResponse + : await client.pathUnchecked(pageLink).get(); + firstRun = false; + checkPagingRequest(result); + const nextLink = getNextLink(result.body, nextLinkName); + const values = getElements(result.body, itemName); + return { + page: values, + nextPageLink: nextLink, + }; + }, + }; + + return getPagedAsyncIterator(pagedResult); +} + +/** + * Gets for the value of nextLink in the body + */ +function getNextLink(body: unknown, nextLinkName?: string): string | undefined { + if (!nextLinkName) { + return undefined; + } + + const nextLink = (body as Record)[nextLinkName]; + + if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { + throw new Error( + `Body Property ${nextLinkName} should be a string or undefined` + ); + } + + return nextLink; +} + +/** + * Gets the elements of the current request in the body. + */ +function getElements(body: unknown, itemName: string): T[] { + const value = (body as Record)[itemName] as T[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` + ); + } + + return value ?? []; +} + +/** + * Checks if a request failed + */ +function checkPagingRequest(response: PathUncheckedResponse): void { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226", + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response + ); + } +} diff --git a/sdk/codesigning/azure-developer-signing-rest/src/parameters.ts b/sdk/codesigning/azure-developer-signing-rest/src/parameters.ts new file mode 100644 index 000000000000..7114a392a24a --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/src/parameters.ts @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { RequestParameters } from "@azure-rest/core-client"; +import { SigningPayloadOptions } from "./models"; + +export type GetSigningStatusParameters = RequestParameters; +export type GetSignRootCertificateParameters = RequestParameters; +export type ListExtendedKeyUsagesParameters = RequestParameters; + +export interface SignBodyParam { + body?: SigningPayloadOptions; +} + +export type SignParameters = SignBodyParam & RequestParameters; diff --git a/sdk/codesigning/azure-developer-signing-rest/src/pollingHelper.ts b/sdk/codesigning/azure-developer-signing-rest/src/pollingHelper.ts new file mode 100644 index 000000000000..b074c18dda54 --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/src/pollingHelper.ts @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { Client, HttpResponse } from "@azure-rest/core-client"; +import { + CreateHttpPollerOptions, + LongRunningOperation, + LroResponse, + OperationState, + SimplePollerLike, + createHttpPoller, +} from "@azure/core-lro"; +import { + Sign202Response, + SignDefaultResponse, + SignLogicalResponse, +} from "./responses"; +/** + * Helper function that builds a Poller object to help polling a long running operation. + * @param client - Client to use for sending the request to get additional pages. + * @param initialResponse - The initial response. + * @param options - Options to set a resume state or custom polling interval. + * @returns - A poller object to poll for operation state updates and eventually get the final response. + */ +export async function getLongRunningPoller< + TResult extends SignLogicalResponse | SignDefaultResponse +>( + client: Client, + initialResponse: Sign202Response | SignDefaultResponse, + options?: CreateHttpPollerOptions> +): Promise, TResult>>; +export async function getLongRunningPoller( + client: Client, + initialResponse: TResult, + options: CreateHttpPollerOptions> = {} +): Promise, TResult>> { + const poller: LongRunningOperation = { + requestMethod: initialResponse.request.method, + requestPath: initialResponse.request.url, + sendInitialRequest: async () => { + // In the case of Rest Clients we are building the LRO poller object from a response that's the reason + // we are not triggering the initial request here, just extracting the information from the + // response we were provided. + return getLroResponse(initialResponse); + }, + sendPollRequest: async (path) => { + // This is the callback that is going to be called to poll the service + // to get the latest status. We use the client provided and the polling path + // which is an opaque URL provided by caller, the service sends this in one of the following headers: operation-location, azure-asyncoperation or location + // depending on the lro pattern that the service implements. If non is provided we default to the initial path. + const response = await client + .pathUnchecked(path ?? initialResponse.request.url) + .get(); + const lroResponse = getLroResponse(response as TResult); + lroResponse.rawResponse.headers["x-ms-original-url"] = + initialResponse.request.url; + return lroResponse; + }, + }; + + options.resolveOnUnsuccessful = options.resolveOnUnsuccessful ?? true; + return createHttpPoller(poller, options); +} + +/** + * Converts a Rest Client response to a response that the LRO implementation understands + * @param response - a rest client http response + * @returns - An LRO response that the LRO implementation understands + */ +function getLroResponse( + response: TResult +): LroResponse { + if (Number.isNaN(response.status)) { + throw new TypeError( + `Status code of the response is not a number. Value: ${response.status}` + ); + } + + return { + flatResponse: response, + rawResponse: { + ...response, + statusCode: Number.parseInt(response.status), + body: response.body, + }, + }; +} diff --git a/sdk/codesigning/azure-developer-signing-rest/src/responses.ts b/sdk/codesigning/azure-developer-signing-rest/src/responses.ts new file mode 100644 index 000000000000..ef215bbf7bdf --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/src/responses.ts @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { RawHttpHeaders } from "@azure/core-rest-pipeline"; +import { HttpResponse, ErrorResponse } from "@azure-rest/core-client"; +import { + OperationStatusOutput, + PagedExtendedKeyUsageOutput, + ResourceOperationStatusOutput, +} from "./outputModels"; + +/** The request has succeeded. */ +export interface GetSigningStatus200Response extends HttpResponse { + status: "200"; + body: OperationStatusOutput; +} + +export interface GetSigningStatusDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface GetSigningStatusDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & GetSigningStatusDefaultHeaders; +} + +/** The request has succeeded. */ +export interface GetSignRootCertificate200Response extends HttpResponse { + status: "200"; + /** Value may contain any sequence of octets */ + body: Uint8Array; +} + +export interface GetSignRootCertificateDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface GetSignRootCertificateDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & GetSignRootCertificateDefaultHeaders; +} + +/** The request has succeeded. */ +export interface ListExtendedKeyUsages200Response extends HttpResponse { + status: "200"; + body: PagedExtendedKeyUsageOutput; +} + +export interface ListExtendedKeyUsagesDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface ListExtendedKeyUsagesDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & ListExtendedKeyUsagesDefaultHeaders; +} + +export interface Sign202Headers { + /** The location for monitoring the operation state. */ + "operation-location": string; +} + +/** The request has been accepted for processing, but processing has not yet completed. */ +export interface Sign202Response extends HttpResponse { + status: "202"; + body: ResourceOperationStatusOutput; + headers: RawHttpHeaders & Sign202Headers; +} + +export interface SignDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface SignDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & SignDefaultHeaders; +} + +/** The final response for long-running sign operation */ +export interface SignLogicalResponse extends HttpResponse { + status: "200"; + body: ResourceOperationStatusOutput; +} diff --git a/sdk/codesigning/azure-developer-signing-rest/src/signingClient.ts b/sdk/codesigning/azure-developer-signing-rest/src/signingClient.ts new file mode 100644 index 000000000000..7fef83195470 --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/src/signingClient.ts @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { getClient, ClientOptions } from "@azure-rest/core-client"; +import { logger } from "./logger"; +import { TokenCredential } from "@azure/core-auth"; +import { SigningClient } from "./clientDefinitions"; + +/** + * Initialize a new instance of `SigningClient` + * @param region - The Azure region wherein requests for signing will be sent. + * @param credentials - uniquely identify client credential + * @param options - the parameter for all optional parameters + */ +export default function createClient( + region: string, + credentials: TokenCredential, + options: ClientOptions = {} +): SigningClient { + const baseUrl = options.baseUrl ?? `https://${region}.codesigning.azure.net/`; + options.apiVersion = options.apiVersion ?? "2023-06-15-preview"; + options = { + ...options, + credentials: { + scopes: options.credentials?.scopes ?? [ + "https://codesigning.azure.net/.default", + ], + }, + }; + + const userAgentInfo = `azsdk-js-developer-signing-rest/1.0.0-beta.1`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` + : `${userAgentInfo}`; + options = { + ...options, + userAgentOptions: { + userAgentPrefix, + }, + loggingOptions: { + logger: options.loggingOptions?.logger ?? logger.info, + }, + }; + + const client = getClient(baseUrl, credentials, options) as SigningClient; + + return client; +} diff --git a/sdk/codesigning/azure-developer-signing-rest/test/public/sampleTest.spec.ts b/sdk/codesigning/azure-developer-signing-rest/test/public/sampleTest.spec.ts new file mode 100644 index 000000000000..bce68e428645 --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/test/public/sampleTest.spec.ts @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { Recorder } from "@azure-tools/test-recorder"; +import { assert } from "chai"; +import { createRecorder } from "./utils/recordedClient"; +import { Context } from "mocha"; + +describe("My test", () => { + let recorder: Recorder; + + beforeEach(async function (this: Context) { + recorder = await createRecorder(this); + }); + + afterEach(async function () { + await recorder.stop(); + }); + + it("sample test", async function () { + assert.equal(1, 1); + }); +}); diff --git a/sdk/codesigning/azure-developer-signing-rest/test/public/utils/env.browser.ts b/sdk/codesigning/azure-developer-signing-rest/test/public/utils/env.browser.ts new file mode 100644 index 000000000000..fd2aca680c7b --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/test/public/utils/env.browser.ts @@ -0,0 +1,2 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. diff --git a/sdk/codesigning/azure-developer-signing-rest/test/public/utils/env.ts b/sdk/codesigning/azure-developer-signing-rest/test/public/utils/env.ts new file mode 100644 index 000000000000..0e06855b73ae --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/test/public/utils/env.ts @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import * as dotenv from "dotenv"; + +dotenv.config(); diff --git a/sdk/codesigning/azure-developer-signing-rest/test/public/utils/recordedClient.ts b/sdk/codesigning/azure-developer-signing-rest/test/public/utils/recordedClient.ts new file mode 100644 index 000000000000..6cc58bc15e11 --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/test/public/utils/recordedClient.ts @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { Context } from "mocha"; +import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import "./env"; + +const envSetupForPlayback: Record = { + ENDPOINT: "https://endpoint", + AZURE_CLIENT_ID: "azure_client_id", + AZURE_CLIENT_SECRET: "azure_client_secret", + AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", + SUBSCRIPTION_ID: "azure_subscription_id", +}; + +const recorderEnvSetup: RecorderStartOptions = { + envSetupForPlayback, +}; + +/** + * creates the recorder and reads the environment variables from the `.env` file. + * Should be called first in the test suite to make sure environment variables are + * read before they are being used. + */ +export async function createRecorder(context: Context): Promise { + const recorder = new Recorder(context.currentTest); + await recorder.start(recorderEnvSetup); + return recorder; +} diff --git a/sdk/codesigning/azure-developer-signing-rest/tsconfig.json b/sdk/codesigning/azure-developer-signing-rest/tsconfig.json new file mode 100644 index 000000000000..d5bf593423c9 --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../../tsconfig.package", + "compilerOptions": { + "outDir": "./dist-esm", + "declarationDir": "./types" + }, + "include": [ + "src/**/*.ts", + "./test/**/*.ts" + ] +} \ No newline at end of file diff --git a/sdk/codesigning/azure-developer-signing-rest/tsp-location.yaml b/sdk/codesigning/azure-developer-signing-rest/tsp-location.yaml new file mode 100644 index 000000000000..3d3f8492015e --- /dev/null +++ b/sdk/codesigning/azure-developer-signing-rest/tsp-location.yaml @@ -0,0 +1,5 @@ +additionalDirectories: [] +commit: 32fe89b5cc906d9840632c3c02b2535633abe445 +directory: specification/codesigning/CodeSigning +repo: Azure/azure-rest-api-specs + diff --git a/sdk/codesigning/ci.yml b/sdk/codesigning/ci.yml new file mode 100644 index 000000000000..016063160881 --- /dev/null +++ b/sdk/codesigning/ci.yml @@ -0,0 +1,33 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: + branches: + include: + - main + - feature/* + - release/* + - hotfix/* + exclude: + - feature/v4 + paths: + include: + - sdk/codesigning/ +pr: + branches: + include: + - main + - feature/* + - release/* + - hotfix/* + exclude: + - feature/v4 + paths: + include: + - sdk/codesigning/ +extends: + template: /eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: codesigning + Artifacts: + - name: azure-rest-developer-signing + safeName: azurerestdevelopersigning