text:
azure identity token refresh issue with msi-adapter

Bug Report

import path of package in question, e.g. /sdk/azidentity
SDK version
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.11.1
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.5.1
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.2.0
output of go version
go 1.22

What happened?
We are using the msi-adapter sidecar to use Azure ARC extension's System Assigned Managed Identity for Azure cloud communication.
While it generally works well, we've noticed that sometimes the sdk doesn't query token on msi-adapter, leading to errors during cloud communication.

RESPONSE 401: 401 Unauthorized
ERROR CODE: ExpiredAuthenticationToken
{
"error": {
"code": "ExpiredAuthenticationToken",
"message": "The access token expiry UTC time '10/16/2024 9:52:23 PM' is earlier than current UTC time '10/16/2024 10:11:14 PM'."
}
}
To us, it seems that the SDK is using some cached value cause msi-adapter shows no logs of any token request from the SDK code.
Almost all subsequent requests failed for at least next ~30 minutes and then started working again.
Below are the logs from our service.
The access token expiry UTC time '10/15/2024 3:40:40 AM' is earlier than current UTC time '10/15/2024 3:42:24 AM'
The access token expiry UTC time '10/15/2024 3:40:40 AM' is earlier than current UTC time '10/15/2024 3:44:24 AM'
The access token expiry UTC time '10/15/2024 3:40:40 AM' is earlier than current UTC time '10/15/2024 4:06:24 AM'.
The access token expiry UTC time '10/15/2024 3:40:40 AM' is earlier than current UTC time '10/15/2024 4:28:24 AM'.
The access token expiry UTC time '10/15/2024 3:40:40 AM' is earlier than current UTC time '10/15/2024 4:50:24 AM'.

What did you expect or want to happen?
Token should have been refreshed if it is expired.
How can we reproduce it?
Anything we should know about your environment.
Code is running on Azure AKS.

Service clients and azidentity credentials both cache access tokens, however each cache checks whether tokens have expired before using them. Can you please explain what msi-adapter is and how your application gets tokens?

@chlowell
The msi-adapter in Azure Arc is a component used to facilitate communication between Azure Arc-enabled resources and Azure services using Managed Service Identity (MSI). It acts as a sidecar container that helps manage the identity and authentication process for Azure Arc extensions.
Here are more details.
https://msazure.visualstudio.com/One/_wiki/wikis/One.wiki/679872/MSI-Adapter
Is there a way to enable sdk logs to check at what time the new token was requested?

Moreover, the following log lines are from the error returned by the SDK;
The access token expiry UTC time '10/15/2024 3:40:40 AM' is earlier than current UTC time '10/15/2024 3:42:24 AM'
The access token expiry UTC time '10/15/2024 3:40:40 AM' is earlier than current UTC time '10/15/2024 3:44:24 AM'
The access token expiry UTC time '10/15/2024 3:40:40 AM' is earlier than current UTC time '10/15/2024 4:06:24 AM'.
The access token expiry UTC time '10/15/2024 3:40:40 AM' is earlier than current UTC time '10/15/2024 4:28:24 AM'.
The access token expiry UTC time '10/15/2024 3:40:40 AM' is earlier than current UTC time '10/15/2024 4:50:24 AM'.
so, it seems the SDK did ot refresh the token before sending making those cloud calls.

Is there a way to enable sdk logs to check at what time the new token was requested?

Yes. If you enable logging as described in the README, you'll get messages like "ManagedIdentityCredential.GetToken() acquired a token..." (add the timestamp in your log listener). This won't tell you whether the token was from the cache; you can determine that from network logs. If you want to inspect a token to check its expiration time, you can use a simple wrapper like
import (
    "github.com/Azure/azure-sdk-for-go/sdk/azcore"
    "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
)

type wrapper struct{
    c azcore.TokenCredential
}

func (w *wrapper) GetToken(ctx context.Context, tro policy.TokenRequestOptions) (azcore.AccessToken, error) {
    tk, err := w.c.GetToken(ctx, tro)
    if err == nil {
        // TODO: inspect or log tk.ExpiresOn
    }
    return tk, err
}

As for what's going wrong in this case, I guess azidentity could get the wrong expiration time if msi-adapter doesn't behave exactly like IMDS. Can you share an example token response from msi-adapter (please omit the token 😆)?

repo: Azure/azure-sdk-for-go


text:
armcompute 5.1.0-beta.1 release

Includes updated codegen for fakes and trace spans.

[ ] The purpose of this PR is explained in this or a referenced issue.
[ ] The PR does not update generated files.

These files are managed by the codegen framework at Azure/autorest.go.

[ ] Tests are included and/or updated for code changes.
[ ] Updates to CHANGELOG.md are included.
[ ] MIT license headers are included in each file.

https://github.com/Azure/azure-sdk-for-go/issues/16613

source: gharchive/pull-request

license: MIT

license_type: permissive

license_source: github-api


text:
Test List Blobs Fix for Invalid XML Characters

Test to check that invalid blob names are parsed correctly when List Flat & List Hierarchy
Changed decoding behavior from base64.StdEncoding.DecodeString to url.QueryUnescape because of error message unmarshalling type *generated.ListBlobsFlatSegmentResponse: illegal base64 data at input byte 4

[x] The purpose of this PR is explained in this or a referenced issue.
[x] The PR does not update generated files.

These files are managed by the codegen framework at Azure/autorest.go.

[x] Tests are included and/or updated for code changes.
[ ] Updates to CHANGELOG.md are included.
[x] MIT license headers are included in each file.

/azp run go - azblob

/check-enforcer evaluate

authors: chlowell siminsavani-msft


text:
[AutoPR engagementfabric/resource-manager] fix Go SDK codegen for engagementfabric

Created to sync https://github.com/Azure/azure-rest-api-specs/pull/4498

This PR has been merged into https://github.com/Azure/azure-sdk-for-go/pull/3336


text:
[FEATURE REQ] Index annotation on a field

Is your feature request related to a problem? Please describe.
I would like to be able to query a date field by sorting it first. Currently, when I simply use spring-data-mongodb I'm getting the following error:
The index path corresponding to the specified order-by item is excluded.
Example:
@Document
public class Data implements Serializable {

    private String id;

    @Indexed
    private LocalDateTime modifiedDate;
}

And query:
new Query().with(Sort.by(Sort.Direction.DESC, "modifiedDate")).limit(1)
Does your azure-spring-data-cosmos library support it?
Describe the solution you'd like
Annotating a field with @Indexed should create an index in CosmoDB.
Describe alternatives you've considered
Otherwise I would need to create an index manually.

Thanks for filing this question, @nadworny; someone from the azure-spring team will follow up with you shortly.

I've just updated an issue to reflect my latest knowledge.

@nadworny  - Can you use @CosmosIndexingPolicy to achieve the same ?

source: gharchive/issue

authors: joshfree kushagraThapar nadworny

repo: Azure/azure-sdk-for-java


text:
Storage - Blobs Cryptography Readme issue

1.
Section Link

Suggestion:

Add link for [error_codes]: https://docs.microsoft.com/rest/api/storageservices/blob-service-error-codes
Add link for [performance_tuning]: https://github.com/Azure/azure-sdk-for-java/wiki/Performance-Tuning

@joshfree, @tg-msft, @kyle-patterson and @rickle-msft for notification

@hongli750210 Thank you for noticing this. We'll get it updated.


text:
Change the messageText and messageId order for updateMessage

Proposed order: messageId, popReceipt, messageText, visibilityTimeout
See what the other languages are doing, if it is consistent talk with them and discussing this change

In .NET we have
public virtual async Task<Response<UpdatedMessage>> UpdateMessageAsync(
    string messageText,
    string messageId,
    string popReceipt,
    TimeSpan visibilityTimeout = default,
    CancellationToken cancellationToken = default)

which puts messageText first to match EnqueueMessage.
I have no problem making this change if other languages would like to.

In Python, we have
def update_message(self, message, visibility_timeout=None, pop_receipt=None,                        content=None, timeout=None, **kwargs):
It can also be used to update the contents of the message.

JS

// * @memberof MessageIdClient

  public async update(
    popReceipt: string,
    message: string,
    visibilityTimeout?: number,
    options: MessageIdUpdateOptions = {}
  ): Promise<Models.MessageIdUpdateResponse>

XStore team agrees that we should have the same order of parameters on these.  The slight preference is towards this ordering: messageText, popReceipt, visibilityTimeout, options.  This seems to order them by most used to least used.

When I raised this with Sima, it was related to my preference that method arguments flow from arguments that identify the object to perform the operation on, and then to follow that with the values to provide to the object. In this way, it reads out as "update messageID / popReceipt to have a messageText as specified". Currently it reads "update to messageText on messageID / popReceipt", which feels back to front. I have a very weak opinion on this though.

Closing this as Java is consistent with .NET

authors: HarshaNalluru JonathanGiles alzimmermsft kurtzeborn rakshith91 sima-zhu tg-msft


text:
[Azure Core] RetryPolicy, Missing getter methods of private final properties

Below private final properties variables could have public getter that for any class that extends RetryPolicy can access the value.
    private final RetryStrategy retryStrategy;
    private final String retryAfterHeader;
    private final ChronoUnit retryAfterTimeUnit;

FYI: @mrm9084

@mrm9084  Can you provide more detail about why these getter is required?

@mssfang In order to extend RetryPolicy the retryStrategy, retryAfterHeader, and retryAfterTimeUnit need to be accessed to override various methods. But as they are private with no getter that isn't possible. I could create a duplicate copy of the values as I passed them to you, but any changes would diverge and the resulting object would have to instances of each value.

@alzimmermsft  @srnagar
Is getter implementation possible or there is a better solution.

There isn't a strong reason I can think of to prevent these properties from being accessed, they just shouldn't be able to be set after instantiation of the immutable class.

@srnagar what do u think? I remember your have some ideas about provide these getters is unnecessary.

@alzimmermsft @mssfang There are 2 feature that we want to add. Fist is that the retry after time should not just take the ms-retry-after value, but take the max value between that and the retryAfterTimeUnit. The second feature we want to add is setting a max retry time for the whole request. i.e. we want the request to last longer than 60s. We can do this by setting a block timeout value, but that will not return the correct error code. We want no more retry requests to happen after the time has past.

@mssfang @alzimmermsft @srnagar After thinking about this a bit more. What we really need is for the RetryPolicy to be more extensible. If shouldRetry and determineDelayDuration were made protected then I would be able to override them in my code. Then if they also passed the retry strategy into the methods then I would be able to use is.

Discussed this with @mrm9084 over a call.

Take the max value between ms-retry-after value and duration computed by calculateRetryDelay() method in RetryStrategy

To enable this, one option is to extend calculateRetryDelay() to include HttpResponse as a param but that will be a breaking change. The other option is to make determineDelayDuration a protected method which will not be a breaking change.

Setting a max retry time for the whole request. i.e. we want the request to last longer than 60s.

To achieve this, adding getters methods or making shouldRetry and determineDelayDuration may not be sufficient. There is still no information about when the first attempt was made and the total time elapsed since then.

authors: alzimmermsft mrm9084 mssfang srnagar


text:
[DO NOT MERGE] Rollback code coverage report generation pipeline steps

This PR is created to be prepared to revert the changes made to publish code coverage report in CI pipelines (PR https://github.com/Azure/azure-sdk-for-java/pull/18086). This change won't be necessary if the report generation works fine for all services. This will be merged if there is a known blocking issue caused by the coverage report generation step to quickly unblock a critical release.

Looks like the change in PR #18086 has not caused any issues. So, closing this PR as it's not required.

Looks like the change in PR #18086 has not caused any issues. So, closing this PR as it's not required.


text:
Don't send ip range in tests.

Some tests started to fail after we started to run tests in same region as storage account is. Looks like this is a case.
https://docs.microsoft.com/en-us/rest/api/storageservices/create-service-sas

The setSasIpRange is also covered in other tests that don't send requests.

/azp run java - storage - tests

/azp run java - storage - tests

/azp run java - storage - tests

/azp run java - storage - tests

/azp run java - storage - tests

/azp run java - storage - tests

/azp run java - storage - tests

/azp run java - storage - tests

/azp run java - storage - ci

/azp run java - storage - ci

/azp run java - storage - tests

/azp run java - storage - tests


text:
Added support for capturing  CosmosException diagnostics on Cosmos Repository and Reactive Cosmos Repository APIs

Description
This PR adds support for capturing CosmosException diagnostics as part of Spring repository / JPA APIs.
Earlier, the diagnostics were missing in cases where error was thrown from CosmosRepository and ReactiveCosmosRepository.
Since ResponseDiagnosticsProcessor contract mentions capturing all the diagnostics for responses received from CosmosDB, this PR adds the support for logging those through ResponseDiagnosticsProcessor
All SDK Contribution checklist:

[x] The pull request does not introduce [breaking changes]
[x] CHANGELOG is updated for new features, bug fixes or other significant changes.
[x] I have read the contribution guidelines.

General Guidelines and Best Practices

[x] Title of the pull request is clear and informative.
[x] There are a small number of commits, each of which have an informative message. This means that previously merged commits do not appear in the history of the PR. For more information on cleaning up the commits in your PR, see this page.

Testing Guidelines

[x] Pull request includes test coverage for the included changes.

/azp run java - cosmos - tests

/azp run java - cosmos - tests


text:
Update springboot compatibility version

As title

/azp run java - spring - compatibility-test

/check-enforcer override


text:
mgmt, workloads, add live tests

Description
Please add an informative description that covers that changes made by the pull request and link all relevant issues.
If an SDK is being regenerated based on a new swagger spec, a link to the pull request containing these swagger spec changes has been included above.
All SDK Contribution checklist:

[ ] The pull request does not introduce [breaking changes]
[ ] CHANGELOG is updated for new features, bug fixes or other significant changes.
[ ] I have read the contribution guidelines.

General Guidelines and Best Practices

[ ] Title of the pull request is clear and informative.
[ ] There are a small number of commits, each of which have an informative message. This means that previously merged commits do not appear in the history of the PR. For more information on cleaning up the commits in your PR, see this page.

Testing Guidelines

[ ] Pull request includes test coverage for the included changes.

API change check
API changes are not detected in this pull request.

/azp run prepare-pipelines

/azp run java - workloads - mgmt - tests


text:
Fix Spring CVEs

Description
Upgrade azure-servicebus-jms to 1.0.2(Fix WS-2020-0408, CVE-2024-29025, CVE-2022-24823, CVE-2021-43797, CVE-2023-34462, CVE-2021-21295)
All SDK Contribution checklist:

[ ] The pull request does not introduce [breaking changes]
[ ] CHANGELOG is updated for new features, bug fixes or other significant changes.
[ ] I have read the contribution guidelines.

General Guidelines and Best Practices

[ ] Title of the pull request is clear and informative.
[ ] There are a small number of commits, each of which have an informative message. This means that previously merged commits do not appear in the history of the PR. For more information on cleaning up the commits in your PR, see this page.

Testing Guidelines

[ ] Pull request includes test coverage for the included changes.

API change check
API changes are not detected in this pull request.

close for azure-servicebus-jms to 1.0.2 is not compatible with jdk8

https://github.com/Azure/azure-servicebus-jms/issues/49

authors: Netyyyy azure-sdk


text:
[Automation] Generate Fluent Lite from Swagger hardwaresecuritymodules#package-2021-11

[Automation] Generate Fluent Lite from Swagger hardwaresecuritymodules#package-2021-11

API change check
APIView has identified API level changes in this PR and created following API reviews.
com.azure.resourcemanager:azure-resourcemanager-hardwaresecuritymodules


text:
Browser-friendly CJS exports in @azure/storage-blob

Is your feature request related to a problem? Please describe.
Currently @azure/storage-blob has Node.js-specific CJS exports, and both browser-friendly and Node.js-specific ESM exports. Due to compatibility requirements we're unable to use ESM modules in our frontend code, we have to use CJS in our Typescript config and then use Webpack to bundle the CJS output.
Describe the solution you'd like
I'd like to have browser-friendly CJS exports for @azure/blob-storage.
Describe alternatives you've considered
Writing my own wrapper around the HTTP API - but that would require a lot of effort.
Additional context
The package.json contains these lines:
"main": "./dist/index.js",
  "module": "./dist-esm/storage-blob/src/index.js",
  "browser": {
    "./dist-esm/storage-blob/src/index.js": "./dist-esm/storage-blob/src/index.browser.js",
    "./dist-esm/storage-blob/src/credentials/StorageSharedKeyCredential.js": "./dist-esm/storage-blob/src/credentials/StorageSharedKeyCredential.browser.js",
    "./dist-esm/storage-blob/src/utils/utils.node.js": "./dist-esm/storage-blob/src/utils/utils.browser.js",
    "./dist-esm/storage-blob/test/utils/index.js": "./dist-esm/storage-blob/test/utils/index.browser.js",
    "./dist-esm/storage-blob/src/BatchUtils.js": "./dist-esm/storage-blob/src/BatchUtils.browser.js",
    "./dist-esm/storage-blob/src/BlobDownloadResponse.js": "./dist-esm/storage-blob/src/BlobDownloadResponse.browser.js",
    "./dist-esm/storage-blob/src/BlobQueryResponse.js": "./dist-esm/storage-blob/src/BlobQueryResponse.browser.js",
    "./dist-esm/storage-blob/src/utils/BufferScheduler.js": "./dist-esm/storage-blob/src/utils/BufferScheduler.browser.js",
    "./dist-esm/storage-common/src/index.js": "./dist-esm/storage-common/src/index.browser.js",
    "fs": false,
    "os": false,
    "process": false
  },

I'm not sure if I understand things correctly, but I think if it contained something like this (along with an index.browser.js file that doesn't import Node.js-specific modules), that should be enough to cover my use case:
"./dist/index.js": "./dist/index.browser.js"

Hopefully it would just be a small change to the code used to generate CJS exports, maybe I could open a pull request to patch it, if only I could find that code... I only see one tsconfig.json and that only builds ESM.

@paulius-valiunas What bundler are you using that doesn't support ESM? Right now we're using rollup to bundle for CJS+Node, but I don't quite understand bundling to CJS just to re-bundle again for the browser.

@paulius-valiunas or did you mean that you can only use require() in your code?

@paulius-valiunas or did you mean that you can only use require() in your code?

yes, we're using a tsconfig that transpiles any import into require.

@paulius-valiunas What bundler are you using that doesn't support ESM? Right now we're using rollup to bundle for CJS+Node, but I don't quite understand bundling to CJS just to re-bundle again for the browser.

We don't "bundle" to CJS, but we compile the Typescript code first, which converts everything to CJS. Then we use Webpack to bundle the compiled Javascript. The problem is that Webpack picks up the CJS exports, at least with our config.

Oh I think I see the trouble, webpack likely isn't pulling in the browser mappings from package.json if it's just resolving main and getting the node-flavored files that are bundled with our CJS rollup build.
Can you share some excerpts about how you are configuring Webpack (or for bonus cookies, provide a small GitHub example repo)?

@xirzec yup that sounds right. Our webpack config isn't all that bloated, so I guess this can act as an example repo:
https://github.com/iTwin/itwinjs-core/blob/master/full-stack-tests/core/webpack.config.js#L39
The code calling @azure/storage-blob is in another repo and it's not very straightforward to find how it's used, but I guess it doesn't matter too much because the webpack config will pick up CJS exports no matter what.
And sorry, I think the typescript config being set to CJS was a red herring. I'm a noob when it comes to frontend stuff, especially webpack, so I was still trying to figure out how everything works while opening this issue.
Right now I see two potential solutions for my problem:

somehow make Webpack use ESM exports for this particular package and some of its dependencies (@azure/core-http comes to mind, I don't know if there are others that would require ESM) - so far I couldn't find any config options that would do exactly this, but I've temporarily added this as a workaround:

resolve: {
  mainFields: ["main", "module"],
  //...
  alias: {
    "@azure/storage-blob$": "@azure/storage-blob/dist-esm/storage-blob/src/index.browser.js",
    "@azure/core-http$": "@azure/core-http/dist-esm/src/coreHttp.js"
  }
},

compile the browser-friendly rollups of this package as both ESM and CJS. I know it's a limited use case, and it might not be worth inflating the package size even more, but that was the first thought I had so I opened this as a suggestion to see if there are objections to it.

2. compile the browser-friendly rollups of this package as both ESM and CJS. I know it's a limited use case, and it might not be worth inflating the package size even more, but that was the first thought I had so I opened this as a suggestion to see if there are objections to it.

@paulius-valiunas we used to provide browser bundle for @azure/storage-blob in v10.  One of the main reasons why we stop publishing it is because it makes sharing dependencies hard if not impossible when multiple azure sdk packages are used together.  Since bundle size is mostly a browser concern, we decided to provide ESM files and let bundlers do their job.

compile the browser-friendly rollups of this package as both ESM and CJS. I know it's a limited use case, and it might not be worth inflating the package size even more, but that was the first thought I had so I opened this as a suggestion to see if there are objections to it.

@paulius-valiunas we used to provide browser bundle for @azure/storage-blob in v10. One of the main reasons why we stop publishing it is because it makes sharing dependencies hard if not impossible when multiple azure sdk packages are used together. Since bundle size is mostly a browser concern, we decided to provide ESM files and let bundlers do their job.

well I'm not suggesting a browser "bundle" in this case, I'm just suggesting you could do the same thing that you did with ESM (exporting both index.js and index.browser.js, same for other files), but with CJS. It wouldn't have to be bundled into one file, just a variant that uses CJS-style imports/exports. That wouldn't change anything about the "main" and "module" fields or the way dependencies are shared, it would just add more entries to the "browser" field. That means it wouldn't affect any usage that is currently "valid", it would just allow for a browser bundler to resolve correctly using CJS in use cases like mine. I think the only potential disadvantage here would be that the npm package would become larger.

well I'm not necessarily suggesting a browser "bundle" in this case

ah sorry I misunderstood. when I saw rollups I thought about bundled as we use rollup to bundle our libraries.

I'm just suggesting you could do the same thing that you did with ESM (exporting both index.js and index.browser.js, same for other files), but with CJS.

If I understand correctly, we would also have the build targeting CommonJS too, then have browsers mapping between NodeJS CJS files and browser CJS files?

If I understand correctly, we would also have the build targeting CommonJS too, then have browsers mapping between NodeJS CJS files and browser CJS files?

Yup, that is what I meant. In my particular use case, even adding a simple "./dist/index.js": "./dist-esm/storage-blob/src/index.browser.js" might work because webpack would just bundle everything anyway. I can't speak for other bundlers, though, because that would force them into using ESM for this package and there might be weird bugs because of conflicts between ESM and CJS.

@paulius-valiunas Something I'm a little confused about is the default for mainFields is
mainFields: ['browser', 'module', 'main'],

To my inexpert eye it looks you're explicitly removing the mapping lookup for browser even though you are bundling for the web. Wouldn't this cause problems with other packages that rely on browser mappings?

@paulius-valiunas Something I'm a little confused about is the default for mainFields is
mainFields: ['browser', 'module', 'main'],

To my inexpert eye it looks you're explicitly removing the mapping lookup for browser even though you are bundling for the web. Wouldn't this cause problems with other packages that rely on browser mappings?

I thought the default was ['module', 'main'] but maybe I was wrong. Either way, in my understanding the browser field has two completely different uses:

npm allows providing an entry point using this field: https://docs.npmjs.com/cli/v8/configuring-npm/package-json#browser
Webpack and other bundlers allow providing browser-specific overrides for specific files, which is the way you're using it in this repository. This isn't an officially supported field by npm, but there's some documentation here.

So Webpack looks for an entry point in the browser field (1) by default, but it won't find any in your packages because they only contain (2). There's another config option that makes Webpack use (2), and I haven't changed that: https://webpack.js.org/configuration/resolve/#resolvealiasfields

There hasn't been any activity in this issue since 3 weeks, is this still under consideration?

I'm not familiar with how npm uses browser directly, I always assumed that it was a bundler-only field and ignored by node/npm. /cc @bterlson for thoughts here.
I think I'm still a bit muddled on how to proceed here. It's possible that when we migrate to conditional imports that we use the browser condition: https://nodejs.org/dist/latest-v16.x/docs/api/packages.html#community-conditions-definitions
Though node itself will ignore it, so I think we'd be back to depending on bundler support for it. Really CJS feels like the legacy case for node and ESM is the future for everyone with browsers likely needing some kind of bundling/tree-shaking at the app level for the near future.

I'll close this issue since we have a workaround and there's little interest in updating CJS code any further. Thanks for the insight.

authors: jeremymeng paulius-valiunas xirzec

repo: Azure/azure-sdk-for-js


text:
Azure OpenAI API doesn't work when tools are being used with streamChatCompletions

Package Name: @azure/openai
Package Version: ^1.0.0-beta.11
Operating system: Win 10
[ ] nodejs

version:  v18.12.1

[ ] browser

name/version: Chrome 121

[ ] typescript

version: 8.19.2

Is the bug related to documentation in

[ ] README.md
[ ] source code documentation
[ ] SDK API docs on https://docs.microsoft.com

Describe the bug
I try to use tools (a new version of function calling) together with streamChatCompletions() and I get either
{
    requestid: '4b00c2f0-0d49-4faf-9ef0-24bb8c5fd155',
    code: 400,
    message: 'Functions are not supported for this API version or this model version. To learn how to user use function calling with Azure OpenAI Service. Please refer to this wiki  https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/function-calling?tabs=python'
  }

or
  {
    requestid: '5746e80b-3523-44bf-a9db-4e1e7cacc8c9',
    code: 500,
    message: "'dict' object has no attribute 'lower'"
  }

To Reproduce
Steps to reproduce the behavior:

Create a GPT-4 deployment in Azure OpenAI Studio with model version 1106-Preview
Try to send a request using sdk

import {
    AzureKeyCredential,
    ChatRequestMessage,
    OpenAIClient,
} from "@azure/openai";

try {
    const client = new OpenAIClient(
        process.env.AOAIEndpoint, // fill with your value
        new AzureKeyCredential(process.env.AOAIKey), // fill with your value
        {
            apiVersion: "2023-12-01-preview", // you can try with other values as well
        }
    );

    const deploymentId = process.env.AOAIDeploymentId; // fill with your value

      let result = await client
          .streamChatCompletions(
              deploymentId,
              [{ role: "user", content: "Call my function", }] as ChatRequestMessage[],
              {
                    temperature: 0,
                    topP: 1,
                    maxTokens: 1000,
                    frequencyPenalty: 0,
                    presencePenalty: 0,
                    azureExtensionOptions: {
                        extensions: [
                            {
                                type: "AzureCognitiveSearch",
                                endpoint: process.env.SearchEndpoint,
                                key: process.env.SearchKey,
                                indexName: process.env.SearchIndex,
                                inScope: false,
                                strictness: 2,
                                topNDocuments: 8,
                                semanticConfiguration: "default",
                                queryType: "vectorSemanticHybrid",
                                fieldsMapping: {},
                                roleInformation: roleInformationPrompt,
                                filter: null,
                                embeddingKey: process.env.AOAIKey,
                                embeddingEndpoint: process.env.EmbeddingEndpoint
                                embeddingDependency: {
                                    type: "DeploymentName",
                                    deploymentName: process.env.EmbeddingDeploymentName
                                },
                            },
                        ],
                    },
                  tools: [
                      {
                          function: someFunction,
                          type: "function",
                      },
                  ],
              }
          )

Expected behavior
A clear and concise description of what you expected to happen.
Tool is called when needed
Screenshots
If applicable, add screenshots to help explain your problem.
Additional context
Add any other context about the problem here.

Thanks for opening this report!
This seems to be a service issue so I'd recommend opening a support ticket in the Azure portal, so our support team can assist you better and resolve it as soon as possible. To open a support ticket, please refer to the guide here.
Also, I wonder, does the same issue manifest when getChatCompletions is being used? Also, does your deployment handle tool calls correctly if azure extensions are not being used?
Thank you for your patience and cooperation. Please let us know if you have any other questions.

Hello,
The issue persists for getChatCompletions as well
Removing azureExtensionOptions from API call resolves the issue for both  getChatCompletions and  streamChatCompletions!

Shall I still issue a ticket to Azure? Are you able to confirm that the issue is not on SDK's side?
Much thanks in advance!

@jmaczan Yes please, this is definitely a service issue, and @minhanh-phan was able to repro it.

Thanks Deyaaeldeen. I have registered an issue in Azure Portal and will let you know about the status when things move on

Hey, so after a joint investigation with Izabela from MS, we confirmed that it's an issue with services availability and the (undocumented) fact that some API versions doesn't play well with AI Search. I think we can close the ticket for now, unless you'd like to incorporate some code that aligns API typings with API version, so some parts of API are not available if user uses a particular API version string.
Let me know if I can help further
Thanks and have a great day!

Thanks a lot for sharing! In this case, let's close it then.

authors: deyaaeldeen jmaczan


text:
[communication] update to identity 2.0.0-beta.4

Updating our azure identity version to incorporate the fixes from https://github.com/Azure/azure-sdk-for-js/pull/15676/files

/azp run js - communication-sms - tests

/azp run js - communication-identity - tests

/azp run js - communication-phone-numbers - tests

/azp run js - communication-identity - tests

/azp run js - communication-phone-numbers - tests


text:
Unblock react native support when using corev2 packages

~This is a WIP. Currently these changes, along with a shims file, allows our packages that depend on core-client to run in react native.~
~ToDo: I've created expo and react-native cli projects that illustrate what shims are needed to get this working. Currently working on getting those samples into this PR.~
This PR has been updated to just include making the changes needed for the corev2 packages to run in react native, assuming that the requisite browser APIs are pollyfilled.

Build is failing due to formatting changes

I believe I've addressed all the feedback, let me know if there are any concerns! The potential negative impact here is extremely small since only the react native bundler will read these new mappings!

authors: chradek ramya-rao-a


text:
Post release automated changes for textanalytics releases

Post release automated changes for azure-ai-text-analytics

/check-enforcer override

authors: azure-sdk deyaaeldeen


text:
Clean up CODEOWNERS

Removing all aliases flagged as invalid by GitHub (meaning they do not have write access to the repo or do not exist.)
For cases where no owners existed for a path, I removed the path.
Feedback welcome if I accidentally removed someone that I shouldn't have.

/check-enforcer evaluate

/check-enforcer override


text:
[engsys] upgrade rush to 5.89.0 and pnpm to 7.26.0

update versions in rush.json
update files added by rush

/check-enforcer override


text:
migrate quota

same error with :https://github.com/Azure/azure-sdk-for-js/pull/25656

API change check
API changes are not detected in this pull request.


text:
[monitor-opentelemetry-exporter] Fix Nested Object Serialization

Packages impacted by this PR
@azure/monitor-opentelemetry-exporter
Issues associated with this PR
https://github.com/microsoft/ApplicationInsights-node.js/issues/1169
Describe the problem that is addressed by this PR
Fixes an issue with serializing legacy Application Insights logs with nested objects.
Are there test cases added in this PR? (If not, why?)
Yes, added in the logUtils.tests file.
Checklists

[x] Added impacted package name to the issue description
[ ] Does this PR needs any fixes in the SDK Generator?** (If so, create an Issue in the Autorest/typescript repository and link it here)
[x] Added a changelog (if necessary)

API change check
API changes are not detected in this pull request.

authors: JacksonWeber azure-sdk


text:
[api-management] Check in missing changes

Packages impacted by this PR
@azure/api-management-custom-widgets-tools
Describe the problem that is addressed by this PR
When building from main, these files showed as modified, just getting them checked in to avoid having a dirty tree

API change check
API changes are not detected in this pull request.

authors: azure-sdk xirzec


text:
Fix #10109: Add version of EnsureCompleted for IAsyncEnumerable

Also add comments to the disabled diagnostics

@pakrym , @tg-msft , I need your approval for this PR

Looks like some tests are hanging.

There are some tests in Microsoft.Azure.KeyVault.Tests that are running for 30 seconds each. Is that expected?

authors: AlexanderSher pakrym

repo: Azure/azure-sdk-for-net


text:
"Microsoft.ManagedIdentity" SDK update generated from API swagger version 2023-01-31

This PR adds support for GA API version 2023-01-31 available in public swagger repo https://github.com/Azure/azure-rest-api-specs/pull/22354
This version is signed off for a public preview.
All changes are generated from swagger schema and test cases added for newly added resources.
There is a breaking change: ListAssociatedResources method is not available in this GA API version

Track 1 is deprecated. Customers can still access FIC functionality in preview version using track1. closing the PR until there is an escalation


text:
[Event Hubs Web Jobs Extensions] Cancellation Token Adjustment

Contributing to the Azure SDK
Please see our CONTRIBUTING.md if you are not familiar with contributing to this repository or have questions.
For specific information about pull request etiquette and best practices, see this section.

API change check
API changes are not detected in this pull request.

authors: azure-sdk m-redding


text:
Update grafana to 2023-09-01

Contributing to the Azure SDK
Please see our CONTRIBUTING.md if you are not familiar with contributing to this repository or have questions.
For specific information about pull request etiquette and best practices, see this section.

API change check
APIView has identified API level changes in this PR and created following API reviews.
Azure.ResourceManager.Grafana

Fixed the API signature, ready to merge. Thanks!

Fixed the API signature, ready to merge. Thanks!

@yjsong11 merged~

authors: archerzz azure-sdk yjsong11


text:
Increment version for oracle releases

Increment package version after release of Azure.ResourceManager.OracleDatabase

/check-enforcer override

authors: azure-sdk jsquire


text:
Include Change Log in Client Packages Nuget

Add CHANGELOG.md to Dataplane package directories.
Include CHANGELOG.md in published package.

Agree with @jsquire, if we are not positive that there would be content added to track 1 changelogs we should not include the empty files and scope this change to track 2 projects

Do we also need to make any changes to ensure these are properly formatted?  Storage also links to Changelog.txt from the package info in the various .csproj so those links should also be updated if we're changing the file names.

Looks like you added one to sdk/keyvault/CHANGELOG.md which I don't think you wanted. They should be under the package directory.

Do we also need to make any changes to ensure these are properly formatted? Storage also links to Changelog.txt from the package info in the various .csproj so those links should also be updated if we're changing the file names.

As part of the versioning work that @danieljurek and @chidozieononiwu  are working on we would like to also automatically add a correctly formatted header for any new versions we update in the projects.

automatically add a correctly formatted header for any new versions

Can we update the PR to include a little more context about what that'll look like, how we're supposed to edit these files so it doesn't get in the way, etc.?

Looks good wrt ServiceBus track-1 side.
There is still development happening and we would like to have the Changelog integration for the track-1 sdk as well.

Can we update the PR to include a little more context about what that'll look like, how we're supposed to edit these files so it doesn't get in the way, etc.?

@tg-msft we don't have that implemented yet so don't stress much about it right now but the goal will be to add a header with the new version and a blank section under whenever our tools update the package versions in the repo. However if what you are looking for is the format of the changelog have a look at https://github.com/Azure/azure-sdk/blob/master/docs/policies/releases.md#changelog-guidance.

/azp run net-client-ci

azp run net - client - ci

/azp run net - client - ci

authors: chidozieononiwu nemakam pakrym tg-msft weshaggard


text:
November relese of Key Vault for Python

Features

[ ] Secure key release
[ ] Local cryptography (as many algorithms - including new - as possible)

Testing

[ ] RBAC
[ ] Backup/restore
[ ] Secure key release
[ ] Local cryptography

Not accurate anymore

authors: heaths lmazuel

repo: Azure/azure-sdk-for-python


text:
PythonSpec.html references are causing two redirects

Issue:
PythonSpec.html is referenced in the following two places:
README.md
sdk/eventhub/azure-eventhubs/HISTORY.md
This causes two client redirects to: https://azure.github.io/azure-sdk/python_introduction.html
Solution:
Update the links to point directly to the python_introduction page.

Thanks @jongio! //cc: @scbedd

Can't find none of the links anymore :(. Sorry @jongio it took so long to look at it, if you can still have this problem, could you create a new issue?
Thanks

authors: jongio kaerm lmazuel


text:
mypy 1.0.0

TODO update docs

Closing in favor for https://github.com/Azure/azure-sdk-for-python/pull/29287


text:
[AutoPR cognitiveservices/data-plane/ContentModerator] Update contentmoderator Node.js package version to 3.0.0

Created to sync https://github.com/Azure/azure-rest-api-specs/pull/3546

(message created by the CI based on PR content)

NodeJS PR

authors: AutorestCI lmazuel


text:
[AutoRelease] t2-containerservicefleet-2023-09-27-30314(can only be merged by SDK owner)

https://github.com/Azure/sdk-release-request/issues/4580
Live test success
https://dev.azure.com/azure-sdk/internal/_build?definitionId=982
BuildTargetingString
azure-mgmt-containerservicefleet
Skip.CreateApiReview
true

issue link:https://github.com/Azure/sdk-release-request/issues/4580


text:
[AutoPR billing/resource-manager] Adding products

Created to sync https://github.com/Azure/azure-rest-api-specs/pull/4063

Codecov Report

Merging #3490 into restapi_auto_billing/resource-manager will decrease coverage by 15.85%.
The diff coverage is 82.55%.

@@                            Coverage Diff                             @@
##           restapi_auto_billing/resource-manager    #3490       +/-   ##
==========================================================================
- Coverage                                   53.5%   37.65%   -15.86%
==========================================================================
  Files                                       5665     8857     +3192
  Lines                                     142829   263732   +120903
==========================================================================
+ Hits                                       76419    99302    +22883
- Misses                                     66410   164430    +98020

Impacted Files
Coverage Δ

...illing/azure/mgmt/billing/operations/operations.py
39.39% <0%> (-2.55%)
:arrow_down:

...t/billing/operations/billing_periods_operations.py
51.35% <100%> (-46.93%)
:arrow_down:

...zure/mgmt/billing/models/enrollment_account_py3.py
50% <100%> (ø)

...-mgmt-billing/azure/mgmt/billing/models/invoice.py
100% <100%> (ø)
:arrow_up:

...-billing/azure/mgmt/billing/models/download_url.py
100% <100%> (ø)
:arrow_up:

...ure/mgmt/billing/operations/invoices_operations.py
47.5% <100%> (-48.71%)
:arrow_down:

azure-mgmt-billing/azure/__init__.py
100% <100%> (ø)
:arrow_up:

...mgmt-billing/azure/mgmt/billing/models/resource.py
100% <100%> (ø)
:arrow_up:

...t-billing/azure/mgmt/billing/models/invoice_py3.py
50% <100%> (ø)

...ng/azure/mgmt/billing/models/billing_period_py3.py
50% <100%> (ø)

... and 5256 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update bc0bbaa...cd09d2d. Read the comment docs.

(message created by the CI based on PR content)

authors: AutorestCI codecov-io


text:
[AutoPR sql/resource-manager] Update Vulnerability Assessment swaggers

Created to sync https://github.com/Azure/azure-rest-api-specs/pull/4394

(message created by the CI based on PR content)

This PR has been merged into https://github.com/Azure/azure-sdk-for-python/pull/3680


text:
Add paralel_tool_calls to azure-ai-inerence API and corresponding tests.

Description
Starting from the API version 2024-09-01-preview the new parameter paralel_tool_calls was added. In this PR we are adding it to Python SDK.
See the specs PR: https://github.com/Azure/azure-rest-api-specs/pull/31684
All SDK Contribution checklist:

[x] The pull request does not introduce [breaking changes]
[x] CHANGELOG is updated for new features, bug fixes or other significant changes.
[x] I have read the contribution guidelines.

General Guidelines and Best Practices

[x] Title of the pull request is clear and informative.
[x] There are a small number of commits, each of which have an informative message. This means that previously merged commits do not appear in the history of the PR. For more information on cleaning up the commits in your PR, see this page.

Testing Guidelines

[x] Pull request includes test coverage for the included changes.

API change check
APIView has identified API level changes in this PR and created following API reviews.
azure-ai-projects


text:
[AutoPR] operationalinsights/resource-manager

Created to accumulate context: operationalinsights/resource-manager

(message created by the CI based on PR content)


text:
Certificates implemented consistency changes besides pollers

fixes #9112

Can one of the admins verify this patch?


text:
Board Review: Azure Notification Hubs (JS)

Contacts and Timeline

Responsible service team: Azure SDK for JS Team
Main contacts: Matthew Podwysocki
Expected code complete date: October 2022
Expected release date: November 2022

About the Service

Link to documentation introducing/describing the service: https://docs.microsoft.com/en-us/azure/notification-hubs/
Link to the service REST APIs: https://aka.ms/nh-rest-api
Link to GitHub issue for previous review sessions, if applicable:  #4489

About the client library

Name of the client library: Azure Notification Hubs
Languages for this review: JavaScript

Artifacts required (per language)
TypeScript

APIView Link: https://apiview.dev/Assemblies/Review/4f7ee36b2e4d446795d81ce35e1faf42
Link to Champion Scenarios/Quickstart samples:

Scenarios: https://gist.github.com/mpodwysocki/44633f26eb48f084c615eed8580ac4a6
Samples: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/samples-dev

Scheduled: Oct 20th, 2022, 2:05PM - 4:00PM PST

authors: mpodwysocki ronniegeraghty

repo: Azure/azure-sdk


text:
Content-Type: Not passed in the Request Headers

From @securityvoid on February 14, 2017 16:44
Hello,
It does not appear that "Content-Type" is handled so that it shows up under:
req.headers
This appears to be true for both Azure Functions Cli and the actual Azure deployments. (Not sure if this means I should open this issue elsewhere).
Interesting this data does appear to be within:
context.bindingData
I can parse this out, but can someone please explain why Content-Type wouldn't be passed with the rest of the headers?
I've got a form-data object that I need to parse to extract a file upload. There are packages that will do this automatically (e.g. busboy), if I pass in the Content-Type/boundary.
It seems weird to me that this wouldn't be included in the details.
Copied from original issue: Azure/azure-functions-cli#68

I do think this should be moved to the runtime repo https://github.com/Azure/azure-webjobs-sdk-script

/cc @fabiocav @mathewc

repo: Azure/azure-webjobs-sdk-script


text:
Linter warning no-hardcoded-env-urls should just tell me what to write.

Is your feature request related to a problem? Please describe.
/workspaces/dbinfra/templates/rg-patient.bicep(35,43) : Warning no-hardcoded-env-urls: Environment URLs should not be hardcoded. Use the environment() function to ensure compatibility across clouds. Found this disallowed host: "core.windows.net" [https://aka.ms/bicep/linter/no-hardcoded-env-urls

Describe the solution you'd like
Instead of telling me about the environment() functions it would be nice if it could tell me the exact expression, I have no idea what to write after environment(). (it turns out it seems to be environment().suffixes.storage it should be in my case :)

That's a great suggestion!

In order to make this work, we would need a mapping of disallowed hosts and the corresponding environment() expression. This will also get complicated if we decide to address #3119 because then the URLs would be per cloud.

@majastrz - I don't think it would be any different with per cloud... the environment() function that you use to "fix" this issue is cloud agnostic, so the "fix" would be the same in any cloud.  The uris/hosts can be a superset.

@bmoore-msft To come up with the code fix, you have to match all the per-cloud URIs to the property in the object returned by environment(). This helps us come up with a codefix that replaces management.azure.us with environment().resourceManager.

Couldn't we just model it for multiple matches, e.g.
if ( management.azure.us or management.azure.com or management.azure.cn ) >> environment().resourceManager

Yup, it looks like we're both saying the same thing.

Have the same issue with https://api.loganalytics.io. I get the warning but can't find any docs about which environment property would have the correct url.

We should also include a lightbulb/quick fix for this.

****. The values for the public cloud are documented here: https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/template-functions-deployment#example-1

ARM also publishes the list of endpoints for all clouds under https://management.azure.com/metadata/endpoints?api-version=2019-05-01

authors: MarcusFelling anthony-c-martin bmoore-msft majastrz mauve pakrym

repo: Azure/bicep


text:
v1.0.7 does not seem to run anything in actions

Hi I'm see the same behaviour as https://github.com/Azure/cli/issues/96 with v1.0.7.
https://github.com/IATI/refresher/actions/runs/3847739483/jobs/6554582341
See "Delete existing container group" step in the above run.
Reverting to v1.0.6 works for me:
https://github.com/IATI/refresher/actions/runs/3847846677/jobs/6554835089

Hi @nosvalds We have updated the ref for v1.0.7 so it should work as expected now.
We suggest using azure/cli@v1 as that will always point to the latest ref.

@t-dedah that worked. I did have it at azure/cli@v1 but was getting warnings about Node 12 because I suppose it was still using v1.0.6 because the v1.0.7 ref with Node 16 was broken...

authors: nosvalds t-dedah

repo: Azure/cli


text:
Fixing bug with only __typename in the selection set

Why make this change?

Closes #1463
Queries and Mutations with only _typename in the selection set fails at the database layer because there are no columns to choose in the database query.

     {
        book_by_pk(id: 1){
             __typename
         }
     }

What is this change?

During the construction of SqlQueryStructure, if it is observed that there are no columns selected, then one of the primary keys is added so that the eventual database query constructed contains a valid column name in the SELECT statement.

How was this tested?

[X] Integration Tests
[X] Manual Tests

Waiting for few answers, perhaps the optimization of not hitting the db can be a followup PR

I would have expected that to be the better approach, since you don't actually need any data back from the DB, but I can see there being a problem when you've done a query like:
query {
  books {
    items {
      __typename
    }
  }
}

That should return a items array that has n __typename properties in it, where n is the count of records in the query (up to 100).

authors: aaronpowell severussundar

repo: Azure/data-api-builder


text:
Hack to allow PDBs to progress

This is needed because the label selector field on the PDB spec has a patch strategy of "replace" meaning that the computed patch will never be empty even if the objects are the same, meaning that we'll never mark the resource as reconciled.

Leaving this comment to block pending discussion on strategic-merge-diff @jveski

repo: Azure/eno


text:
Add generation of ArmResourceSpec interface

Fix up a few package exclusions to happen a bit earlier (cleaning up some hacky code we had a TODO about).

Coverage remained the same at ?% when pulling 85bef22fc02daed2ec8523098bed9c1ea04e2963 on matthchr:feature/arm-spec-interface into d1d18d130162477d6c1c29a3376b54b7948ba771 on Azure:master.

authors: coveralls matthchr


text:
feat(timeout): Implement customizable timeout for Azure CLI token ret…

This commit introduces the ability to specify a custom timeout for Azure CLI token retrieval within the kubelogin package. The AzureCLIToken struct now includes a timeout field, allowing users to set a specific timeout duration.

@microsoft-github-policy-service agree [company="AIFI"]

https://github.com/Azure/azure-sdk-for-go/issues/21985
https://github.com/Azure/azure-sdk-for-go/issues/21985#issuecomment-1813444765

Looking forward to it!

@weinong can you run the CI please?
golangci-lint run
pkg/token/federatedIdentity.go:65:15: string `/.default` has 3 occurrences, make it a constant (goconst)
		resource += "/.default"
		            ^
 ```
 Also, am I meant to fix this with a global const?

I believe I also fixed the tests.

I now see the timeout correctly in the convert-kubeconfig sub command, and its no longer wedged into the main kubelogin command.
./kubelogin convert-kubeconfig --timeout

linting is now passing my changes locally as well

I now see the timeout in both of the sub commands, and I am no longer wedging the --timeout into the main kubelogin command.
./kubelogin get-token --timeout 90s
./kubelogin convert-kubeconfig --timeout 90s
however we don't really pass the option to the the convert-kubeconfig subcommand..
convert.go root.go token.go
I'm only expecting to see it as an option in the get-token
./kubelogin  get-token --help | grep timeout
      --timeout duration                     Timeout duration for Azure CLI token requests (default 30s)
./kubelogin  convert-kubeconfig --help | grep timeout
      --timeout duration                     Timeout duration for Azure CLI token requests (default 30s)

do you know what I did wrong?

@Aricg , get-token and convert-kubeconfig share identical flags because convert-kubeconfig adds the flags to get-token command. Can you update the logic in convert.go so that it appends --timeout when that flag is used in convert-kubeconfig?

@Aricg , get-token and convert-kubeconfig share identical flags because convert-kubeconfig adds the flags to get-token command. Can you update the logic in convert.go so that it appends --timeout when that flag is used in convert-kubeconfig?

Hi @weinong convert-kubeconfig uses the network?
I don't think I want to add a timeout to this command.

@Aricg convert-kubeconfig doesn't do network calls. It generally copy the flags into a kubecofig using get-token sub-command. It's fine you don't add it, if you don't find it a problem cracking up the kubeconfig to add the flag. Besides using the --timeout, a better usability may be via environment variable so that you don't need to update kubeconfig all the time.

go test -race -coverprofile=coverage.txt -covermode=atomic ./...
?   	github.com/Azure/kubelogin	[no test files]
?   	github.com/Azure/kubelogin/pkg/cmd	[no test files]
?   	github.com/Azure/kubelogin/pkg/token/mock_token	[no test files]
ok  	github.com/Azure/kubelogin/pkg/converter	1.988s	coverage: 90.0% of statements
ok  	github.com/Azure/kubelogin/pkg/pop	3.279s	coverage: 76.9% of statements
ok  	github.com/Azure/kubelogin/pkg/testutils	1.652s	coverage: 9.2% of statements
ok  	github.com/Azure/kubelogin/pkg/token	34.407s	coverage: 67.6% of statements

:)

Codecov Report
Attention: 7 lines in your changes are missing coverage. Please review.

Comparison is base (369f19a) 65.02% compared to head (52ca6b1) 64.98%.

Files
Patch %
Lines

pkg/token/options.go
36.36%
5 Missing and 2 partials :warning:

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #362      +/-   ##
==========================================
- Coverage   65.02%   64.98%   -0.05%
==========================================
  Files          23       23
  Lines        1710     1728      +18
==========================================
+ Hits         1112     1123      +11
- Misses        536      541       +5
- Partials       62       64       +2

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

authors: Aricg codecov-commenter weinong

repo: Azure/kubelogin


text:
Azure/login github action always looks for 'environment' entity type despite specifying other entity types in app registration

Hello, I'm trying to use 'OIDC federated credentials' using app registration -> federation credentials.  Azue/login github actions always looks for entity type 'environment' despite specifying other entity type such as 'pull_request'.
If I specify 'environment' in entity_type in app registration, the github actions works:
Run azure/login@v1
  with:
    client-id: <client-id>
    subscription-id: <sub-id>
    tenant-id: <tenant-id>
    enable-AzPSSession: false
    environment: azurecloud
    allow-no-subscriptions: false
    audience: api://AzureADTokenExchange
Using OIDC authentication...
Federated token details:
 issuer - https://token.actions.githubusercontent.com
 subject claim - repo:<org/repo>:environment:terraform-demo

If I specify any other type of 'entity type', the github action still looks for enviornment entity type as below:
Run azure/login@v1
Using OIDC authentication...
Federated token details:
 issuer - https://token.actions.githubusercontent.com
 subject claim - repo:<org/repo>:environment:terraform-demo
/usr/bin/az cloud set -n azurecloud
Done setting cloud: "azurecloud"
Error: : AADSTS70021: No matching federated identity record found for presented assertion. Assertion Issuer: 'https://token.actions.githubusercontent.com'. Assertion Subject: 'repo:<org/repo>:environment:terraform-demo'. Assertion Audience: 'api://AzureADTokenExchange'.
Trace ID: 3940b0d0-43bf-4048-a7bb-8fea435ab300
Correlation ID: 58e6c5ab-e623-4b92-9a53-a9b0ce85ee6d
Timestamp: 2022-01-15 10:55:55Z

@pavanm-huma Looks like you are trying to access any secret or something which is present in an environment. That's why it is expecting you to have those federated credentials to be present for the environment. Please share your workflow for a better understanding of the issue.

@BALAGA-GAYATRI Thanks for the response!  I do not intend to use any secrets for authentication -- I only want to use federated credentials using OIDC provider to have short lived tokens only.
Below is my composite action (action.yml)
    - name: 'Az CLI login'
      if: ${{ inputs.azure_client_id != '' && inputs.azure_sub_id != '' }}
      uses: azure/login@v1
      with:
        client-id: ${{ inputs.azure_client_id }}
        subscription-id: ${{ inputs.azure_sub_id }}
        tenant-id: ${{ inputs.azure_tenant_id }}

The above composite action is invoked by the main workflow as below:
      - id: plan-action
        uses: ./.github/actions
        with:
            action-type : 'plan'
            modules-token: ${{ secrets.modules_token }}
            target-folder: ${{ github.event.inputs.target-folder != '' && github.event.inputs.target-folder || '<folder>' }}
            target-module: ${{ github.event.inputs.target-module != '' && github.event.inputs.target-module || '' }}
            azure_client_id: '<client-id>'
            azure_sub_id: '<sub-id>'

@pavanm-huma Can you please confirm -

How are you triggering the workflow in failure case? pull_request event? If yes, make sure the federated credentials are generated for that event.
Also what exactly is terraform-demo ? github environment?

I think your workflow requires terraform-demo environment's FIC for some reason. Also you can try setting two separate credentials one for environment and the other for pull_request event and give a try.

@BALAGA-GAYATRI Yes, it is triggered from pull request.  Federated credentials are already configured.  The above 2 scenarios (one success and one failure) is against federated credentials with 2 different settings -- details below:

If entity type is set to 'environment' (yes, environment is defined in my workflow as well to match to it), it works.

If entity type is set to any other say, pull_request, it doesn't work.  The problem I believe is, azure/login github action always looks for environment against the app registration.

So for the failure case(triggering via pull_request) also using the environment (terraform)? @kjyam98 Can you help here?

@BALAGA-GAYATRI I'm not familiar with terraform...have you tried reproducing the error?

Hi Gayatri, yes, we are still facing the same issue.  Any help would be
appreciated.
On Wed, 23 Feb 2022 at 16:58, Balaga Gayatri @.***>
wrote:

@pavanm-huma https://github.com/pavanm-huma Can you tell the latest
status of the issue? Still facing the problem?
—
Reply to this email directly, view it on GitHub
https://github.com/Azure/login/issues/197#issuecomment-1048997372, or
unsubscribe
https://github.com/notifications/unsubscribe-auth/AT7C6VNQLGH76ORCHYQKE33U4UGZRANCNFSM5MBFGR7A
.
Triage notifications on the go with GitHub Mobile for iOS
https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675
or Android
https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub.
You are receiving this because you were mentioned.Message ID:
@.***>

--
Pavan Kumar Mayakuntla (he/him)
Lead DevOps Engineer
‘Nobel prize of pharma’ Prix Galien USA
https://huma.com/thoughtpiece/prixgalienaward winner for digital health
Europe’s fastest-growing healthcare company Financial Times
https://hubs.la/H0RXdCr0
Funding to date $250 million https://hubs.la/H0RXdCB0
See how we supported patients during the Covid-19 pandemic
https://hubs.la/H0RXdy50
Discover our product range: Hospital at home
https://hubs.la/H0RXdCT0 | Decentralized
clinical trials https://hubs.la/H0RXdD70 | Digital biomarkers
https://hubs.la/H0RXdC_0

Hi @pavanm-huma, If I understood correctly you are running workflow using an environment that is triggered by a pull request event.  And your FIC is configured with the PullRequest entity type.  This won't work, because if the workflow is using an environment then the sub claim always contains Environment details only. So change the FIC entity type to Environment and try.

Just for reference , here is the doc that clarifies the point @kchandra548 mentioned above : https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect#filtering-for-pull_request-events

@pavanm-huma Were you able to solve your issue using the above solution? Do let us know.

@pavanm-huma assuming the above comments and referred docs helped you with azure login action and closing this issue. Feel free to reopen this issue if are still facing the problem. We will be happy to help you.

repo: Azure/login


text:
FileOntologyMappingLoader exception handling

The malformed mapping file error case (i.e., JsonSerializer.Deserialize throwing JsonException) is now caught and wrapped with explanation in MappingFileException. The latter has an additional constructor to accept such an inner exception.
First fixes ported over from #105

Need to update the version number in the csproj to as part of this

Need to update the version number in the csproj to as part of this

Wanted to do this at the very end in case some other PR got merged first, but have now updated to 0.6.6.

authors: hammar joebeernink

repo: Azure/opendigitaltwins-tools


text:
JS file not being returning GZIP'd for Static Web App

When I view my static web app, I noticed that the response for my JS files are not returned with gzip encoding. According to this documentation, GZIP compression is automatically supposed to happen for JS files
To reproduce

Go to https://www.bobharing.com/ with dev tools opened (using Edge Version 120.0.2210.91 (Official build) (arm64))
View the https://www.bobharing.com/assets/js/app.058755c5.js file in the network tab.
The request header mentions
Accept-Encoding: gzip, deflate, br
When you look in the response headers, there is no content-encoding header present.

Expected behavior
JS file has GZIP encoding.
Screenshots

There is not content-encoding header present for the JS file.
Device info (if applicable):

OS: MACOS (arm64)
Browser Edge
Version Version 120.0.2210.91 (Official build) (arm64)

Additional context
There is the same issue for the CSS files.

Are you using "Enterprise-grade edge"?
We're experiencing this issue specifically when it's enabled. Compression works without it.
See issue #1340

I can also repro the behaviour of Enterprise Edge enabled vs disabled on content served via ASWA:

Same here. Is there any workaround available without disabling Enterprise Edge?

@sebiJo I've been told that a fix is in progress and should be released in October.

@sebiJo @bobharing @ImpactMAC  I got a message that the fix has been deployed but you need to disable / re-enable enterprise edge for the fix to take.

Thanks a lot for the Update @HowardvanRooijen !
I have disabled enterprise edge yesterday in production and compression works as expected now without enterprise edge. 24 hours later, I am trying re-enable enterprise edge but it says that it cannot update because another update would be still in progress. Oh man ...

authors: HowardvanRooijen ImpactMAC bobharing sebiJo

repo: Azure/static-web-apps


text:
[AVM Module Issue]: Cannot lock down module version.

Check for previous/existing GitHub issues

[X] I have checked for previous/existing GitHub issues

Issue Type?
Bug
(Optional) Module Version
0.2.0
(Optional) Correlation Id
No response
Description
│
│ Could not download module "databricks_workspace_apac" (main.tf:945) source code from
│ "git::https://github.com/Azure/terraform-azurerm-avm-res-databricks-workspace.git?ref=v0.2.0": error downloading
│ 'https://github.com/Azure/terraform-azurerm-avm-res-databricks-workspace.git?ref=v0.2.0': C:\Program Files\Git\cmd\git.exe exited with 1: error: pathspec
│ 'v0.2.0' did not match any file(s) known to git

Apparently you can lock it down without the v in the string. So I used "?ref=0.2.0" instead of the more common approach which would be "?ref=v0.2.0". Could you add to the next batch of changes?


text:
chore: repository governance

Repository governance update
This PR was automatically created by the AVM Team hive-mind using the grept governance tool.
We have detected that some files need updating to meet the AVM governance standards.
Please review and merge with alacrity.
Grept config source: git::https://github.com/Azure/Azure-Verified-Modules-Grept.git//terraform
Thanks! The AVM team :heart:

Supersceeded by #22


text:
chore: repository governance

Repository governance update
This PR was automatically created by the AVM Team hive-mind using the grept governance tool.
We have detected that some files need updating to meet the AVM governance standards.
Please review and merge with alacrity.
Grept config source: git::https://github.com/Azure/Azure-Verified-Modules-Grept.git//terraform
Thanks! The AVM team :heart:

Supersceeded by #83


text:
Trusted Signing Action not producing log analytics or storage account logs

Hi!
Is this a known issue I might have overseen?
I just enabled the Diagnostic Settings in Azure to drop logs into a Storage Account and another setting for a log analytics workspace.
It's been a few days now an no logs are being created.

hey @mosaickai could you share on which region did you attempted to perform signing?

Hi!
We're running trusted signing from [West Europe].
Do we have to have 'Trace logging' enabled in the task?

@mosaickai We're reaching out to the team to take a look at this.

Thank you!

authors: Jaxelr mosaickai

repo: Azure/trusted-signing-action


text:
Deployment failure marked as passed

I've just had a run (https://github.com/PREreview/prereview/runs/3289511938) log:
Restarting app service: prereview-dev
Deployment passed
Restarted app service: prereview-dev
Successfully updated deployment History at ...

But it failed due to a misconfiguration, the deployment log containing:
INFO - Stopping site prereview-dev because it failed during startup.

Is it possible to check that the deployment has actually worked?

hey @thewilkybarkid Can you add this secret in your repo ACTIONS_STEP_DEBUG and set its value to true to enable detailed debug logs and that might solve the issue. Also please share your workflow if the problem persists. Do let us know if it works.

@thewilkybarkid : did you tried above suggestion and let us know if that helped ?

@thewilkybarkid I am marking this issue closed for now. Please re-open if the above suggestion did not work out and share workflow.

authors: BALAGA-GAYATRI rahulaga-dev rahulaga-msft thewilkybarkid

repo: Azure/webapps-deploy


text:
查别人角色 只返回八个

https://api-takumi.mihoyo.com/game_record/app/genshin/api/index

已修复


text:
Refactor getRequestAuthorityWithExtraQP in AdalBrokerRequestAdapter

The logic here looks into extra QP and checks for slice/dc and will ad to Authority and removes those extra QP params. Seems a bit rough, and there is scope to improve it. https://github.com/AzureAD/microsoft-authentication-library-common-for-android/pull/433/files/846df27508abe92e6fd55de4f050aece61236956#diff-3bceaa5e3e93d643181941a6c0daa0d0R256

Removing the assignee as they are no longer contributing to this project.

authors: iambmelt kreedula


text:
Removing low-perf fix for duplication BAM data

The fix originally done in #1232 can be implemented to avoid performing multiple reads of BAM data. This PR ensures the data is read just 1x and relies on a few things...

SharedPreferencesFileManagerSimpleCacheImpl can now be initialized with a flag allowing calls to insert() to replace the existing element, even if the existing/new element have the same hashCode() - for backcompat, this behavior is disabled by default
BrokerApplicationMetadata no longer considers foci state to be criteria for equality - this likely should have always been this way

These changes are covered by existing tests here

Changelog?

Changelog?

in 5b8807a43eacf870f4d20572d6cc932dbf055db5

Somewhat related to #1427 - different kinds of optimizations for reading/writing BAM data

authors: AdamBJohnsonx iambmelt


text:
TypeScript Error: "Declaration or statement expected." in msal-browser/dist/src/index.d.ts

Library

[ ] msal@1.x.x or @azure/msal@1.x.x
[x] `@azure/msal-browser@2.0.0-beta.2
[ ] @azure/msal-angular@0.x.x
[ ] @azure/msal-angular@1.x.x
[ ] @azure/msal-angularjs@1.x.x

Framework
react@16.12.0 with typescript@3.7.5
Description
When including the @azure/msal-browser in the project, the following error appears:
TypeScript error in D:/project_name/node_modules/@azure/msal-browser/dist/src/index.d.ts(5,1):
Declaration or statement expected.  TS1128

    3 | export { BrowserAuthError, BrowserAuthErrorMessage } from "./error/BrowserAuthError";
    4 | export { BrowserConfigurationAuthError, BrowserConfigurationAuthErrorMessage } from "./error/BrowserConfigurationAuthError";
  > 5 | export type { AuthCallback } from "./types/AuthCallback";
      | ^
    6 | export { AuthenticationParameters, TokenExchangeParameters, AuthResponse, TokenResponse, InteractionRequiredAuthError, AuthError, AuthErrorMessage, INetworkModule, Logger, LogLevel } from "@azure/msal-common";

Security
No.
Regression
Don't know.
Configuration
Please provide your MSAL configuration options.
// Provide configuration values here.
// For Azure B2C issues, please include your policies.

Expected behavior
When export type { AuthCallback } from './types/AuthCallback' is changed to export { AuthCallback } from './types/AuthCallback' it is compiling successfully.
Could be related to my tsconfig
{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}

Browsers
Is this issue browser-specific? If so, please detail which browsers are impacted (e.g. IE 11, Safari).''
No.

@ninio Could you try upgrading to Typescript 3.8? This version introduced type-only imports and exports which is why you may be seeing the above error.

The update fixes this.
Thanks!

Solved me issue,  you may want to add this to the documentation on getting started. I am upgrading a project that was using older version of TypeScript and was hitting this error.

authors: jrmcdona ninio pkanher617


text:
Azure AD B2C sample cannot acquire accessToken

Core Library
MSAL.js v2 (@azure/msal-browser)
Core Library Version
azure/msal-browser@2.13.1
Wrapper Library
Not Applicable
Wrapper Library Version
None
Description
Using the Azure AD B2C samples outlined here  and here, I have successfully been able to authenticate using a signup / signin flow.
However when I click the Call API button, the response contains an idToken but no accessToken. MSAL goes through the process of acquiring a token through popup, but that fails too.
I have confirmed that my registered app is set up to issue both access and id tokens:

Error Message
This error is happening because the accessToken is blank:
api.js:15 GET http://localhost:5000/hello 401 (Unauthorized)
callApi @ api.js:15
(anonymous) @ authPopup.js:147
Promise.then (async)
passTokenToApi @ authPopup.js:143
onclick @ (index):39
api.js:25 SyntaxError: Unexpected token U in JSON at position 0
(anonymous) @ api.js:25
Promise.catch (async)
callApi @ api.js:24
(anonymous) @ authPopup.js:147
Promise.then (async)
passTokenToApi @ authPopup.js:143
onclick @ (index):39
Msal Logs
[Thu, 16 Sep 2021 21:06:42 GMT] :  : @azure/msal-browser@2.13.1 : Info - Emitting event: msal:acquireTokenStart
authConfig.js:31 [Thu, 16 Sep 2021 21:06:42 GMT] :  : @azure/msal-browser@2.13.1 : Info - Emitting event: msal:acquireTokenFromNetworkStart
authConfig.js:31 [Thu, 16 Sep 2021 21:06:43 GMT] :  : @azure/msal-browser@2.13.1 : Info - Emitting event: msal:acquireTokenSuccess
authPopup.js:125 Silent token acquisition fails. Acquiring token using popup.
InteractionRequiredAuthError
at InteractionRequiredAuthError.AuthError [as constructor] (index.es.js:422)
at InteractionRequiredAuthError.ServerError [as constructor] (index.es.js:2778)
at new InteractionRequiredAuthError (index.es.js:3666)
at authPopup.js:120
authConfig.js:31 [Thu, 16 Sep 2021 21:06:43 GMT] :  : @azure/msal-browser@2.13.1 : Info - Emitting event: msal:acquireTokenStart
authConfig.js:31 [Thu, 16 Sep 2021 21:06:43 GMT] :  : @azure/msal-browser@2.13.1 : Info - Emitting event: msal:popupOpened
authConfig.js:31 [Thu, 16 Sep 2021 21:06:44 GMT] :  : @azure/msal-common@4.1.1 : Info - in acquireToken call
authConfig.js:31 [Thu, 16 Sep 2021 21:06:45 GMT] :  : @azure/msal-browser@2.13.1 : Info - BrowserCacheManager.cleanRequestByState: Removing temporary cache items for state: eyJpZCI6ImU2MDU2YzJjLWU5MWItNDEyNC05MWJjLWUyNTA3NzdiMTljMiIsIm1ldGEiOnsiaW50ZXJhY3Rpb25UeXBlIjoicG9wdXAifX0=
authConfig.js:31 [Thu, 16 Sep 2021 21:06:45 GMT] :  : @azure/msal-browser@2.13.1 : Info - Emitting event: msal:acquireTokenSuccess
authPopup.js:130 {authority: 'https://ambaguest.b2clogin.com/ambaguest.onmicrosoft.com/b2c_1_signupsignin1/', uniqueId: '21397728-62d1-4837-bd1d-db3dd9844adf', tenantId: '', scopes: Array(0), account: {…}, …}
authPopup.js:145 access_token acquired at: Thu Sep 16 2021 16:06:45 GMT-0500 (Central Daylight Time)
MSAL Configuration
/**
 * Configuration object to be passed to MSAL instance on creation.
 * For a full list of MSAL.js configuration parameters, visit:
 * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md
 * For more details on using MSAL.js with Azure AD B2C, visit:
 * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/working-with-b2c.md
 */

const msalConfig = {
    auth: {
      clientId: "eeff946f-5d1a-43db-885f-bbb4f662a848", // This is the ONLY mandatory field; everything else is optional.
      authority: b2cPolicies.authorities.signUpSignIn.authority, // Choose sign-up/sign-in user-flow as your default.
      knownAuthorities: [b2cPolicies.authorityDomain], // You must identify your tenant's domain as a known authority.
      redirectUri: "http://localhost:6420", // You must register this URI on Azure Portal/App Registration. Defaults to "window.location.href".
    },
    cache: {
      cacheLocation: "sessionStorage", // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO between tabs.
      storeAuthStateInCookie: false, // If you wish to store cache items in cookies as well as browser cache, set this to "true".
    },
    system: {
      loggerOptions: {
        loggerCallback: (level, message, containsPii) => {
          if (containsPii) {
            return;
          }
          switch (level) {
            case msal.LogLevel.Error:
              console.error(message);
              return;
            case msal.LogLevel.Info:
              console.info(message);
              return;
            case msal.LogLevel.Verbose:
              console.debug(message);
              return;
            case msal.LogLevel.Warning:
              console.warn(message);
              return;
          }
        }
      }
    }
  };

/**
 * Scopes you add here will be prompted for user consent during sign-in.
 * By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.
 * For more information about OIDC scopes, visit:
 * https://docs.microsoft.com/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
 */
const loginRequest = {
  scopes: ["openid", ...apiConfig.b2cScopes],
};

/**
 * Scopes you add here will be used to request a token from Azure AD B2C to be used for accessing a protected resource.
 * To learn more about how to work with scopes and resources, see:
 * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/resources-and-scopes.md
 */
const tokenRequest = {
  scopes: ["https://ambaguest.onmicrosoft.com/eeff946f-5d1a-43db-885f-bbb4f662a848/User.Read", ...apiConfig.b2cScopes],  // e.g. ["https://fabrikamb2c.onmicrosoft.com/helloapi/demo.read"]
  forceRefresh: false // Set this to "true" to skip a cached token and go to the server to get a new token
};

Relevant Code Snippets
apiConfig.js:
// The current application coordinates were pre-registered in a B2C tenant.
const apiConfig = {
    b2cScopes: ["https://ambaguest.onmicrosoft.com/eeff946f-5d1a-43db-885f-bbb4f662a848/User.Read"],
    webApi: "http://localhost:5000/hello"
  };

authConfig.js:
/**
 * Configuration object to be passed to MSAL instance on creation.
 * For a full list of MSAL.js configuration parameters, visit:
 * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md
 * For more details on using MSAL.js with Azure AD B2C, visit:
 * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/working-with-b2c.md
 */

const msalConfig = {
    auth: {
      clientId: "eeff946f-5d1a-43db-885f-bbb4f662a848", // This is the ONLY mandatory field; everything else is optional.
      authority: b2cPolicies.authorities.signUpSignIn.authority, // Choose sign-up/sign-in user-flow as your default.
      knownAuthorities: [b2cPolicies.authorityDomain], // You must identify your tenant's domain as a known authority.
      redirectUri: "http://localhost:6420", // You must register this URI on Azure Portal/App Registration. Defaults to "window.location.href".
    },
    cache: {
      cacheLocation: "sessionStorage", // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO between tabs.
      storeAuthStateInCookie: false, // If you wish to store cache items in cookies as well as browser cache, set this to "true".
    },
    system: {
      loggerOptions: {
        loggerCallback: (level, message, containsPii) => {
          if (containsPii) {
            return;
          }
          switch (level) {
            case msal.LogLevel.Error:
              console.error(message);
              return;
            case msal.LogLevel.Info:
              console.info(message);
              return;
            case msal.LogLevel.Verbose:
              console.debug(message);
              return;
            case msal.LogLevel.Warning:
              console.warn(message);
              return;
          }
        }
      }
    }
  };

/**
 * Scopes you add here will be prompted for user consent during sign-in.
 * By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.
 * For more information about OIDC scopes, visit:
 * https://docs.microsoft.com/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
 */
const loginRequest = {
  scopes: ["openid", ...apiConfig.b2cScopes],
};

/**
 * Scopes you add here will be used to request a token from Azure AD B2C to be used for accessing a protected resource.
 * To learn more about how to work with scopes and resources, see:
 * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/resources-and-scopes.md
 */
const tokenRequest = {
  scopes: [...apiConfig.b2cScopes],  // e.g. ["https://fabrikamb2c.onmicrosoft.com/helloapi/demo.read"]
  forceRefresh: false // Set this to "true" to skip a cached token and go to the server to get a new token
};

Reproduction Steps

Install and configure both demo apps.
Start both demo apps.
Navigate to http://localhost:6420
Click 'Call API'

Expected Behavior
Expected to get a 200 OK response from the web api app.
Identity Provider
Azure B2C Basic Policy
Browsers Affected (Select all that apply)
Chrome
Regression
No response
Source
External (Customer)

@jasonbrice In Azure Portal > App Registration, please uncheck the boxes under the Implicit grant and hybrid flows section, as this sample was meant to work with authorization code flow with PKCE, not implicit flow.

I've unchecked both boxes and saved the app, same results.

@jasonbrice apologies, my bad this wasn't related to your issue. For some reason the scopes field looks empty in your acquireTokenPopup response (the last screenshot), so can you clarify what is the exact request object you are passing to that API?

I'm assuming that the scope for the accessToken is in the authConfig.js ?

I've tried plugging the values "openid", "offline_access", ...apiConfig.b2cScopes, and the URI of the api I exposed: "https://ambaguest.onmicrosoft.com/eeff946f-5d1a-43db-885f-bbb4f662a848/User.Read"

@jasonbrice Ok that must be the issue, you cannot mix scopes for different resources in the same token request, take a look at our documentation on this. Basically, make sure only the scope for your web API goes into the tokenRequest object (i.e. https://ambaguest.onmicrosoft.com/eeff946f-5d1a-43db-885f-bbb4f662a848/User.Read), openid and offline_access are MS Graph scopes.

Ok, I've changed the b2cScopes in apiConfig.js to the one I created:

I've changed the scopes in the authConfig.js to match:

I'm still getting a blank access token... I tried both with the boxes unchecked and then rechecking the boxes.
Any ideas?

@jasonbrice are you signing in with an admin account? In the screenshot you shared (the second one here), you choose "only admins can consent to this scope". Did you grant admin consent to this scope in your client application's app registration?

authors: derisen jasonbrice


text:
Authority provided in login request or PublicClientApplication config does not match the environment of the provided account

Core Library
MSAL.js (@azure/msal-browser)
Core Library Version
2.11.x
Wrapper Library
MSAL React (@azure/msal-react)
Wrapper Library Version
none
Public or Confidential Client?
Public
Description
Hi!
For some reason, it worked before, now it stopped working locally. We are getting this error below: Anything that we are missing? Thanks!
https://localhost.nwie.net:3000/
test error type -->  ClientConfigurationError: authority_mismatch: Authority mismatch error. Authority provided in login request or PublicClientApplication config does not match the environment of the provided account. Please use a matching account or make an interactive request to login to this authority.
    at ClientConfigurationError.AuthError [as constructor] (AuthError.ts:49:1)
    at ClientConfigurationError.ClientAuthError [as constructor] (ClientAuthError.ts:222:1)
    at new ClientConfigurationError (ClientConfigurationError.ts:115:1)
    at ClientConfigurationError.createAuthorityMismatchError (ClientConfigurationError.ts:315:1)
    at SilentCacheClient.<anonymous> (BaseInteractionClient.ts:143:1)
    at step (MindbreezeClientService.ts:37:1)
    at Object.next (MindbreezeClientService.ts:37:1)
    at fulfilled (MindbreezeClientService.ts:37:1)
    at nrWrapper ((index):64:35611)

MSAL Configuration
No response
Relevant Code Snippets
const loginRequest = {
  scopes: ["openid", "profile", "User.Read"]
}

export const tokenRequest = {
  scopes: [
    "user.read",
  ]
}

const tokenRequestForceRefresh = {
  scopes: ["User.Read"],
  forceRefresh: true,
}

export let myMSALObj = new PublicClientApplication(msalConfig);
export let username = "";

export function hasActiveMsalSession(): boolean {
  return !!username;
}

function getTokenRedirect(request:any) {
  /**
   * See here for more info on account retrieval:
   * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/Accounts.md
   */
  const currentAccount = myMSALObj.getAllAccounts();

  request.account = currentAccount;
  return myMSALObj.acquireTokenSilent(request).catch(error => {
    console.warn("MsalAuthService >>> getTokenRedirect : Silent token acquisition fails. acquiring token using redirect");
    if (error instanceof Msal.InteractionRequiredAuthError) {
      // fallback to interaction when silent call fails
      console.log("test MSAL acquireTokenSilent - if");
      return myMSALObj.acquireTokenRedirect(request);
    } else {
      console.log("test error type --> ", error);
      console.log("test MSAL acquireTokenSilent - else");
      console.warn("MsalAuthService >>> getTokenRedirect : "+ error);
    }
  });
}

export function getAccessToken(): Promise<string> {
  return getTokenRedirect(loginRequest).then(response => {
    if (!response || !response.accessToken) {
      return "";
    } else {
      return response.accessToken;
    }
  })
}

export function getIdTokenFromAzure(): Promise<string> {
  return getTokenRedirect(loginRequest).then(response => {
    if (!response || !response.idToken) {
      return "";
    } else {
      return response.idToken;
    }
  })
}

function getMindbreezeHeaders(numberOfCallAttempts: number = 0): Promise<any> {
  return getIdTokenFromAzure().then(accessToken => {
    //Check if the response is null or has errors, if it is/does, retry getting the access token up to 5 times
    if (numberOfCallAttempts >= 5) {
      //Will return a 401 error on trying to make the request but prevents the page from erroring due to resp being null..
      //Future: Possibly add logging to Splunk with error and user data
      return null;
    }
    else if (!accessToken) {
      return getMindbreezeHeaders(numberOfCallAttempts + 1);
    }
    else {
      return accessToken;
    }
  });
}

/** Get Authorization jwt token for request to Mindbreeze */
export const getAuthorizationToken = (): any => {
  return getIdTokenFromAzure().then(token => {
    // return token ? `Bearer ${token}` : false;
    console.log("test --- ", token);
    if(token) {
      sessionStorage.setItem("idToken.for.search", `Bearer ${token}`)
      return `Bearer ${token}`;
    }
    return false;
  })
}

export const isTokenCurrent = (token:string): boolean => {
  let decodedToken = jwt_decode<JwtPayload>(token);
  let currentDate = new Date();
  let result = true;

  if(decodedToken?.exp && currentDate.getTime() > (decodedToken.exp * 1000)) {
      result = false;
  }
  return result;
}

export const getMindbreezeHeadersWithForceRefresh = (): any => {
  return getIdTokenFromAzureWithForceRefresh().then(token => {
    // return token ? `Bearer ${token}` : false;
    if(token) {
      sessionStorage.setItem("idToken.for.search", `Bearer ${token}`)
      return `Bearer ${token}`;
    }
    return false;
  })
}

export const getIdTokenFromAzureWithForceRefresh =(): Promise<string> => {
  return getTokenRedirect(tokenRequestForceRefresh).then(response => {
    if (!response || !response.idToken) {
      return "";
    } else {
      return response.idToken;
    }
  })
}

Identity Provider
Azure AD / MSA
Source
External (Customer)

@fong1999 can we see the MSAL config? Also, if you can send a Fiddler trace to the e-mail on my profile that would help diagnose the issue. The error suggests the user account does not belong to the authority the token is being requested from.

Thanks much for your response!
Do you mean this configuration?
export const msalConfig: Msal.Configuration = {
auth: {
clientId: EnvironmentService.getAzureClientId(),
redirectUri: ${window.location.origin},
authority: https://login.microsoftonline.com/${EnvironmentService.getAzureTenantId()}
},
cache: {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: true,
}
}
I will send you the trace tomorrow.
Thanks!

@hectormmg Hi Hector,
Sorry, I am allowed to share the trace info. But I was able to compare the trace between my local and prod.
I see the difference is the my local trace:
Localhost has below, but prod does not.
"stsservicecookie=estsfd; path=/; secure; samesite=none; httponly",
Any ideas?
Thanks!

@hectormmg
Hi Hector,
I am just following up on this issue. Please let me know if you need more information.
Thanks so much!

@hectormmg
Hi Hector, we found out that the @msal-browser latest version is causing the issue we are facing. We had to use version 2.37.0 to fix it. Any information on any known issue with version 2.37.1?
    "@azure/msal-browser": "2.37.0",
    "@azure/msal-react": "1.5.2",

https://www.npmjs.com/package/@azure/msal-browser/v/2.37.1
https://www.npmjs.com/package/@azure/msal-browser?activeTab=versions
Thanks!

Hey @fong1999 , can you confirm that the environment set in your account object that is being passed to acquireTokenSilent API matches or is an alias of the authority you have specified in your login request or the MSAL config? Note that the authority provided in the login request takes higher priority, so please check there first!

@lalimasharda Hi, Thanks for your reply! Yes, we verified that there is no Azure SSO configuration and react code changes to the app. With the updating the library version number as a workaround, we were able to solve the issue. But we had to catch an error for Chrome browser.
  .catch(err => {
    console.error(err);
  })

Any information on any known issue with version 2.37.1?
Thanks!

Also on another note, in your code snippet below, it does not seem that you are passing in the correct account object. Can you please cross check once? :
function getTokenRedirect(request:any) {
const currentAccount = myMSALObj.getAllAccounts();
request.account = currentAccount;
return myMSALObj.acquireTokenSilent(request).catch(error => {  ...

@lalimasharda Thank you for the suggestions!
Here is the current code snippet: What are we missing? Thanks!
function getTokenRedirect(request:any) {
  /**
   * See here for more info on account retrieval:
   * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/Accounts.md
   */
  const currentAccount = myMSALObj.getAllAccounts();

  request.account = currentAccount;
  console.log("testing -- request.account: ", request.account);
  return myMSALObj.acquireTokenSilent(request).catch(error => {
    console.warn("MsalAuthService >>> getTokenRedirect : Silent token acquisition fails. acquiring token using redirect");
    if (error instanceof Msal.InteractionRequiredAuthError) {
      // fallback to interaction when silent call fails
      console.log("testing -- request.account: in if : ", request.account);
      return myMSALObj.acquireTokenRedirect(request);
    } else {
      console.log("testing -- request.account: in else : ", request.account);
      console.log("test error type --> ", error);
      console.log("test MSAL acquireTokenSilent - else");
      console.warn("MsalAuthService >>> getTokenRedirect : "+ error);
    }
  });
}

const currentAccount = myMSALObj.getAllAccounts();
This method will return an array of all accounts in cache and not just the current one. You should try getActiveAccount() instead to get the current active account.

@hectormmg  Thanks for the info!
What do you think below code snippet that is from another front end app that we manage? Will the way that we are setting setActiveAccount helps with the issue we have?  Thanks!
if (!BrowserUtils.isIframe()) {
  myMSALObj = new Msal.PublicClientApplication(msalConfig);
  // Redirect: once login is successful and redirects with tokens, call Graph API
  myMSALObj.handleRedirectPromise().then(handleResponse).catch(err => {
    console.error(err);
  });
}

export function hasActiveMsalSession(): boolean {
  return !!username;
}

function handleResponse(resp) {
  if (resp !== null) {
    username = resp.account.username;
    myMSALObj.setActiveAccount(resp.account);
  } else {
    /**
     * See here for more info on account retrieval:
     * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/Accounts.md
     */
    const currentAccounts = myMSALObj.getAllAccounts();
    if (currentAccounts === null) {
      return;
    } else if (currentAccounts.length > 1) {
      // Add choose account code here
      console.warn("MsalAuthService >>> handleResponse >>> Multiple accounts detected.");
    } else if (currentAccounts.length === 0) {
      signIn();
    } else if (currentAccounts.length === 1) {
      username = currentAccounts[0].username;
      myMSALObj.setActiveAccount(currentAccounts[0]);
    }
  }
}

function signIn() {
  myMSALObj.loginRedirect(loginRequest);
}

function getTokenRedirect(request) {
  /**
   * See here for more info on account retrieval:
   * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/Accounts.md
   */
  return myMSALObj.acquireTokenSilent(request).catch(error => {
    console.warn("MsalAuthService >>> getTokenRedirect : Silent token acquisition fails. acquiring token using redirect");
    if (error instanceof Msal.InteractionRequiredAuthError) {
      // fallback to interaction when silent call fails
      return myMSALObj.acquireTokenRedirect(request);
    } else {
      console.warn("MsalAuthService >>> getTokenRedirect : " + error);
    }
  });
}

Yes, the above code snippet looks good to me.

Yes, the above code snippet looks good to me for setActiveAccount but you also have to call getActiveAccount() to get the current active account that is required in AcquireTokenSilent requests.

@lalimasharda Hi! Thank you for your suggestion!
Where should I call getActiveAccount()? Could you please share an example?
Thanks much in advance!

authors: fong1999 hectormmg lalimasharda


text:
Current Logged in User's access token is stored inside the web browsers local Storage

Core Library
MSAL.js (@azure/msal-browser)
Wrapper Library
MSAL Angular (@azure/msal-angular)
Public or Confidential Client?
Public
Documentation Location
https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser
Description
Logged in User's access token is stored inside the web browsers HTML localStorage, this has been flagged by our Security partners as vulnerable, please suggest on this issue?
Please refer the below Screen Shot:

Cache location is configurable and can be set to memoryStorage if you have concerns with local or session storage. Please note however that there are drawbacks with this option, namely loss of persistence across page refresh. We do not believe there are inherent security risks with localStorage as long as you are not vulnerable to XSS based attacks. Please see this doc for more information about storage configurations and recommendations.

authors: maisteringadmin tnorling


text:
About turn on the laptop with the type-c device plugged(monitor)

First, thanks a lot for your EFI file sharing(Your EFI file is very comprehensive, and can bring a better experience about hacintosh on x1c 5th). Then, I use x1c 5th too, and this is my configuration (https://github.com/HeartAndSoul001/my-EFI-for-x1-carbon-5th/blob/master/README.md). And now, I have one question that the monitor built in will not be lighten when power on with type-c device plug(a 4k monitor). So, I want to consult you about it if you have the same problem too and please give me some advice. In addition, I want to consult you about how to open hidpi on external monitor. Looking forward to your reply as soon as possible >_<

@B0hrer

What resolution is your built-in display? The EDID override in my config is for a 1080p one.

my built-in display is 1080p too. But I can not figure out it

I believe there are some patches for 4k output. You can get some additional infos in this issue I believe. The repo is for the 6th gen x1c, but it's basically the same machine and the repo is maintained by far more knowledgeable people than me.

ok, thanks a lot. I will share you if I figure out it _