Skip to content

Commit c138441

Browse files
authored
Fix credential issue in hlc (#1956)
* Fix credential issue * Update the default value if addcredential is true * Update the UTs * Update the unit test * update the test cases
1 parent 47adf85 commit c138441

8 files changed

Lines changed: 239 additions & 30 deletions

File tree

packages/autorest.typescript/src/generators/clientFileGenerator.ts

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -220,7 +220,12 @@ export function generateClient(clientDetails: ClientDetails, project: Project) {
220220
apiVersionParams && apiVersionParams.length === 1
221221
? apiVersionParams[0]
222222
: undefined;
223-
writeClassProperties(clientClass, clientParams, importedModels, clientDetails.hasTenantLevelOperation);
223+
writeClassProperties(
224+
clientClass,
225+
clientParams,
226+
importedModels,
227+
clientDetails.hasTenantLevelOperation
228+
);
224229
writeConstructor(clientDetails, clientClass, importedModels, apiVersionParam);
225230
if (useCoreV2 && apiVersionParam) {
226231
writeCustomApiVersion(clientClass);
@@ -349,7 +354,7 @@ function writeConstructor(
349354
type: optionsParameterType
350355
}
351356
]
352-
}
357+
};
353358

354359
let clientConstructor;
355360
if (clientDetails.hasTenantLevelOperation) {
@@ -376,7 +381,7 @@ function writeConstructor(
376381
}
377382
]
378383
});
379-
clientConstructor.addOverload(clientConstructorInitial)
384+
clientConstructor.addOverload(clientConstructorInitial);
380385
clientConstructor.addOverload({
381386
parameters: [
382387
...requiredParams
@@ -396,7 +401,9 @@ function writeConstructor(
396401
]
397402
});
398403
} else {
399-
clientConstructor = classDeclaration.addConstructor(clientConstructorInitial);
404+
clientConstructor = classDeclaration.addConstructor(
405+
clientConstructorInitial
406+
);
400407
}
401408

402409
const { useCoreV2 } = getAutorestOptions();
@@ -647,11 +654,8 @@ function getTrack2DefaultContent(
647654
packageDetails: PackageDetails,
648655
clientDetails: ClientDetails
649656
) {
650-
const {
651-
azureArm,
652-
allowInsecureConnection,
653-
addCredentials
654-
} = getAutorestOptions();
657+
const { azureArm, allowInsecureConnection } = getAutorestOptions();
658+
const { addCredentials } = getSecurityInfoFromModel(clientDetails.security);
655659

656660
const overloadDefaults = `
657661
let subscriptionId: string | undefined;
@@ -663,7 +667,9 @@ function getTrack2DefaultContent(
663667
}
664668
`;
665669

666-
const defaultContent = `${clientDetails.hasTenantLevelOperation ? overloadDefaults: ""}
670+
const defaultContent = `${
671+
clientDetails.hasTenantLevelOperation ? overloadDefaults : ""
672+
}
667673
// Initializing default values for options
668674
if (!options) {
669675
options = {};
@@ -731,8 +737,10 @@ function writeDefaultOptions(
731737
hasLro: boolean,
732738
clientDetails: ClientDetails
733739
) {
734-
const { useCoreV2, packageDetails, addCredentials } = getAutorestOptions();
735-
const { credentialScopes } = getSecurityInfoFromModel(clientDetails.security);
740+
const { useCoreV2, packageDetails } = getAutorestOptions();
741+
const { credentialScopes, addCredentials } = getSecurityInfoFromModel(
742+
clientDetails.security
743+
);
736744

737745
const credentialScopesValues = getCredentialScopesValue(
738746
credentialScopes,

packages/autorest.typescript/src/utils/schemaHelpers.ts

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ export function getTypeForSchema(
154154
}
155155
break;
156156
case SchemaType.AnyObject:
157-
kind = PropertyKind.Dictionary
157+
kind = PropertyKind.Dictionary;
158158
typeName = `Record<string, unknown>`;
159159
break;
160160
case SchemaType.Number:
@@ -236,8 +236,8 @@ export function getSecurityInfoFromModel(security: Security) {
236236
for (const securitySchema of security.schemes) {
237237
if (securitySchema.type === "OAuth2") {
238238
(securitySchema as OAuth2SecurityScheme).scopes.forEach(scope => {
239-
const scopes = scope.split(',');
240-
for(const scope of scopes) {
239+
const scopes = scope.split(",");
240+
for (const scope of scopes) {
241241
credentialScopes.add(scope);
242242
}
243243
});
@@ -258,13 +258,21 @@ export function getSecurityInfoFromModel(security: Security) {
258258
);
259259
}
260260
}
261-
const scopes: string[] = [];
262-
credentialScopes.forEach(item => {
263-
scopes.push(item);
264-
});
261+
const scopes: string[] = [...credentialScopes];
262+
let refinedAddCredentials =
263+
addCredentials === false ? false : security.authenticationRequired;
264+
// Add default info if explictly set the addCredentials as true
265+
if (
266+
addCredentials === true &&
267+
!security.authenticationRequired &&
268+
scopes.length === 0 &&
269+
credentialKeyHeaderName === ""
270+
) {
271+
refinedAddCredentials = true;
272+
scopes.push("https://management.azure.com/.default");
273+
}
265274
return {
266-
addCredentials:
267-
addCredentials === false ? false : security.authenticationRequired,
275+
addCredentials: refinedAddCredentials,
268276
credentialScopes: scopes,
269277
credentialKeyHeaderName: credentialKeyHeaderName
270278
};

packages/autorest.typescript/test/commands/test-swagger-gen.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -862,7 +862,7 @@ let testSwaggers: { [name: string]: SwaggerConfig } = {
862862
packageName: "petstore",
863863
useCoreV2: true,
864864
allowInsecureConnection: true,
865-
addCredentials: false,
865+
addCredentials: true,
866866
isTestPackage: true,
867867
coreHttpCompatMode: true
868868
},
Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,27 @@
1+
import { now } from "lodash";
12
import { PetStore as PetStoreClient } from "./generated/corecompattest/src";
23
import { assert } from "chai";
34

45
describe("Integration tests for Core Comapability", () => {
56
let client: PetStoreClient;
67

78
it("should create a client successfully", async () => {
8-
client = new PetStoreClient({
9-
keepAliveOptions: {
10-
enable: true
9+
client = new PetStoreClient(
10+
{
11+
getToken: async () => {
12+
assert.equal(1, 1);
13+
return { token: "FakeToken", expiresOnTimestamp: now() };
14+
}
1115
},
12-
redirectOptions: {
13-
handleRedirects: true
16+
{
17+
keepAliveOptions: {
18+
enable: true
19+
},
20+
redirectOptions: {
21+
handleRedirects: true
22+
}
1423
}
15-
});
24+
);
1625
assert.notEqual(client, null);
1726
});
1827
});

packages/autorest.typescript/test/integration/generated/corecompattest/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
"engines": { "node": ">=14.0.0" },
88
"dependencies": {
99
"@azure/core-client": "^1.7.0",
10+
"@azure/core-auth": "^1.3.0",
1011
"@azure/core-http-compat": "^1.2.0",
1112
"@azure/core-rest-pipeline": "^1.12.0",
1213
"tslib": "^2.2.0"

packages/autorest.typescript/test/integration/generated/corecompattest/src/petStore.ts

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as coreClient from "@azure/core-client";
22
import * as coreHttpCompat from "@azure/core-http-compat";
3+
import * as coreAuth from "@azure/core-auth";
34
import * as Parameters from "./models/parameters";
45
import * as Mappers from "./models/mappers";
56
import {
@@ -43,15 +44,24 @@ export class PetStore extends coreHttpCompat.ExtendedServiceClient {
4344

4445
/**
4546
* Initializes a new instance of the PetStore class.
47+
* @param credentials Subscription credentials which uniquely identify client subscription.
4648
* @param options The parameter options
4749
*/
48-
constructor(options?: PetStoreOptionalParams) {
50+
constructor(
51+
credentials: coreAuth.TokenCredential,
52+
options?: PetStoreOptionalParams
53+
) {
54+
if (credentials === undefined) {
55+
throw new Error("'credentials' cannot be null");
56+
}
57+
4958
// Initializing default values for options
5059
if (!options) {
5160
options = {};
5261
}
5362
const defaults: PetStoreOptionalParams = {
54-
requestContentType: "application/json; charset=utf-8"
63+
requestContentType: "application/json; charset=utf-8",
64+
credential: credentials
5565
};
5666

5767
const packageDetails = `azsdk-js-petstore/1.0.0-preview1`;
@@ -60,6 +70,9 @@ export class PetStore extends coreHttpCompat.ExtendedServiceClient {
6070
? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
6171
: `${packageDetails}`;
6272

73+
if (!options.credentialScopes) {
74+
options.credentialScopes = ["https://management.azure.com/.default"];
75+
}
6376
const optionsWithDefaults = {
6477
...defaults,
6578
...options,
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
# Azure KustoManagement client library for JavaScript
2+
3+
This package contains an isomorphic SDK (runs both in Node.js and in browsers) for Azure KustoManagement client.
4+
5+
The Azure Kusto management API provides a RESTful set of web services that interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and delete clusters and databases.
6+
7+
[Source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/kusto/arm-kusto) |
8+
[Package (NPM)](https://www.npmjs.com/package/@azure/arm-kusto) |
9+
[API reference documentation](https://docs.microsoft.com/javascript/api/@azure/arm-kusto?view=azure-node-preview) |
10+
[Samples](https://github.com/Azure-Samples/azure-samples-js-management)
11+
12+
## Getting started
13+
14+
### Currently supported environments
15+
16+
- [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule)
17+
- Latest versions of Safari, Chrome, Edge and Firefox.
18+
19+
See our [support policy](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) for more details.
20+
21+
### Prerequisites
22+
23+
- An [Azure subscription][azure_sub].
24+
25+
### Install the `@azure/arm-kusto` package
26+
27+
Install the Azure KustoManagement client library for JavaScript with `npm`:
28+
29+
```bash
30+
npm install @azure/arm-kusto
31+
```
32+
33+
### Create and authenticate a `KustoManagementClient`
34+
35+
To create a client object to access the Azure KustoManagement API, you will need the `endpoint` of your Azure KustoManagement resource and a `credential`. The Azure KustoManagement client can use Azure Active Directory credentials to authenticate.
36+
You can find the endpoint for your Azure KustoManagement resource in the [Azure Portal][azure_portal].
37+
38+
You can authenticate with Azure Active Directory using a credential from the [@azure/identity][azure_identity] library or [an existing AAD Token](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-with-a-pre-fetched-access-token).
39+
40+
To use the [DefaultAzureCredential][defaultazurecredential] provider shown below, or other credential providers provided with the Azure SDK, please install the `@azure/identity` package:
41+
42+
```bash
43+
npm install @azure/identity
44+
```
45+
46+
You will also need to **register a new AAD application and grant access to Azure KustoManagement** by assigning the suitable role to your service principal (note: roles such as `"Owner"` will not grant the necessary permissions).
47+
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`.
48+
49+
For more information about how to create an Azure AD Application check out [this guide](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal).
50+
51+
```javascript
52+
const { KustoManagementClient } = require("@azure/arm-kusto");
53+
const { DefaultAzureCredential } = require("@azure/identity");
54+
// For client-side applications running in the browser, use InteractiveBrowserCredential instead of DefaultAzureCredential. See https://aka.ms/azsdk/js/identity/examples for more details.
55+
56+
const client = new KustoManagementClient(new DefaultAzureCredential());
57+
58+
// For client-side applications running in the browser, use this code instead:
59+
// const credential = new InteractiveBrowserCredential({
60+
// tenantId: "<YOUR_TENANT_ID>",
61+
// clientId: "<YOUR_CLIENT_ID>"
62+
// });
63+
// const client = new KustoManagementClient(credential);
64+
```
65+
66+
67+
### JavaScript Bundle
68+
To use this client library in the browser, first you need to use a bundler. For details on how to do this, please refer to our [bundling documentation](https://aka.ms/AzureSDKBundling).
69+
70+
## Key concepts
71+
72+
### KustoManagementClient
73+
74+
`KustoManagementClient` is the primary interface for developers using the Azure KustoManagement client library. Explore the methods on this client object to understand the different features of the Azure KustoManagement service that you can access.
75+
76+
## Troubleshooting
77+
78+
### Logging
79+
80+
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`:
81+
82+
```javascript
83+
const { setLogLevel } = require("@azure/logger");
84+
setLogLevel("info");
85+
```
86+
87+
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).
88+
89+
## Next steps
90+
91+
Please take a look at the [samples](https://github.com/Azure-Samples/azure-samples-js-management) directory for detailed examples on how to use this library.
92+
93+
## Contributing
94+
95+
If you'd like to contribute to this library, please read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) to learn more about how to build and test the code.
96+
97+
## Related projects
98+
99+
- [Microsoft Azure SDK for JavaScript](https://github.com/Azure/azure-sdk-for-js)
100+
101+
![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fkusto%2Farm-kusto%2FREADME.png)
102+
103+
[azure_cli]: https://docs.microsoft.com/cli/azure
104+
[azure_sub]: https://azure.microsoft.com/free/
105+
[azure_sub]: https://azure.microsoft.com/free/
106+
[azure_portal]: https://portal.azure.com
107+
[azure_identity]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity
108+
[defaultazurecredential]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#defaultazurecredential

0 commit comments

Comments
 (0)