Authentication to access other parts of Azure DevOps within a custom task - azure-devops

I want to create a Azure DevOps custom task that accesses other parts of Azure DevOps. Specifically, I want to create a custom task that adds a comment to a PR.
Unfortunately, I can't figure out how to authenticate properly. I found this code and added it to my task:
let token: string = tl.getEndpointAuthorizationParameter("SYSTEMVSSCONNECTION", "AccessToken", false);
let collectionUrl: string = tl.getEndpointUrl("SYSTEMVSSCONNECTION", false).replace(".vsrm.visualstudio.com", ".visualstudio.com");
let authHandler = token.length === 52 ? vsts.getPersonalAccessTokenHandler(token) : vsts.getBearerHandler(token);
let connection = new vsts.WebApi(collectionUrl, authHandler);
but I get the error:
TF401027: You need the Git 'PullRequestContribute' permission to perform this action. Details: identity 'Build\XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', scope 'repository'.
I verified that the build service should have the correct permissions:
I've also tried checking the box "Allow scripts to access the OAuth token" in the Job settings, but that had no effect.
What am I missing?

You need to give permissions to the build users:
In Microsoft hosted agent is "Build Service (user-name)" and "Project Collection Build Service (Project)" (Sometimes the last only show up if you type the UUID (8837...) on "Search for user or groups".)
Can be found in project settings > repositories > permissions

I think you should use the "System.AccessToken" variable to get the token:
tl.getVariable('System.AccessToken');
Predefined build variables - System.AccessToken
I use that in my build task: https://github.com/ashamrai/AzureDevOpsExtensions/blob/master/CustomBuildTask/NewWICustomTask/index.ts

Related

Create a release pipeline in Azure DevOps which uploads a file to LCS, with a non admin user that doesn't have MFA

I'm trying to create a release pipeline in DevOps, that releases packages to LCS. The normal Dynamics 365 FO way of working. The issue is, I don't have an admin account without MFA that can be used to do this. Which roles or general setup, should I set on the AAD user, to be able to create the release? Currently I'm getting the AADSTS7000218 error.
I created a user that doesn't have MFA and I expect to add certain roles to be able to use this user for creating releases in DevOps.
In Azure DevOps, to create release pipeline you need "Edit release pipeline" permission set to Allow. And you need to be at least a Basic user.
And as per the document, AADSTS7000218 means The request body must contain the following parameter: 'client_assertion' or 'client_secret'. When authenticating to Azure AD to get an access token, the client application is not providing its “password” (in the form of either a client secret or a client assertion) as expected by Azure AD’s token endpoint.
You could try navigating to Azure Active Directory->App Registration and find Authentication in your application. And set "Allow public client flows" to "Yes" in Azure portal.
Here's another ticket has the similar issue, hope it can help.

Azure DevOps Client SDK: Using TestManagementHttpClient.GetTestResultsByBuildAsync2 throws auth error

I am using the .NET client library for Azure DevOps to get test results from a build attempt. The following throws an authentication error, Microsoft.VisualStudio.Services.Common.VssUnauthorizedException: VS30063: You are not authorized to access https://dev.azure.com.
var testClient = connection.GetClient<TestManagementHttpClient>();
var testResults = await testClient.GetTestResultsByBuildAsync2(
project: project,
buildId: ID);
I am using a PAT that is scoped to read and execute Builds and Tests. Not sure why I'm getting this error. Is there another way to get test results per attempt? I am able to use this same connection to call GetTestResultDetailsForBuildAsync but unfortunately, that lists results for all the attempts and I just need the last one.
Try either of the following ways to resolve Microsoft.VisualStudio.Services.Common.VssUnauthorizedException: VS30063: You are not authorized to access https://dev.azure.com. error:
Clean the cache as suggested by Marina Liu:Execute
regedit -> clean key(s) under
HKEY_CURRENT_USER\Software\Microsoft\VSCommon\14.0\ClientServices\TokenStorage\VisualStudio\VssApp
-> restart VS -> run your project with your own credential.
Check whether Personal Access Token has expired or created with the right Scope or not
References: VS30063: You are not authorized to access https://dev.azure.com? Error while trying to register Private agent Pool in Azure DevOps Project using PAT token - Microsoft Q&A , c# - VS30063: You are not authorized to access https://dev.azure.com - Stack Overflow and Visual Studio Feedback

The service connection does not exist or has not been authorized for use

I'm trying to create my first release pipeline, however I keep getting this error:
Exception Message: The pipeline is not valid. Job Phase_1: Step AzureResourceGroupDeployment input ConnectedServiceName references service connection
which could not be found. The service connection does not exist or has not been authorized for use. For authorization details,
refer to https://aka.ms/yamlauthz. (type PipelineValidationException)
I've tried to follow the instructions in the link, however the "Authorize Resources" button does not exist.
"Allow all pipelines to use this service connection" is already enabled and I have recreated the deployment task after enabling this.
How do I authorise the resource?
I had the same issue, and I initally missed the fact that you need to click the 'Authorize resources' button that appears, as shown below
Also in my case, my pipeline was missing variables that included the correct service connection name. These were set up in a variable group that was already being used by another pipeline. I needed to link them in my new pipeline:
Edit pipeline > select elipsis at top right > triggers > Variables > Variable groups > Link variable group
You can either use existing Service principal or create a new one. All you need is in documentation already.
Create an Azure Resource Manager service connection using automated security
From Azure DevOps -> Project setting -> Service connection: Then click on "New Service Connection".Choose "Azure resource Manager" as type of service connection. Select Service Principal (Automatic). Run your pipeline
My "Service connection" which defined the service principal connection had been created separately to the task in my release pipeline.
In order for "Authorize Resources" to occur, you must create a new connection from the task itself (you may need to use the advanced options to add an existing service principal).
under "Azure subscription" click the name of the subscription you wish to use
Click the drop down next to "Authorize" and open advanced options
Click " use the full version of the service connection dialog."
Enter all your credentials and hit save
The admittely silly solution for me was to avoid declaring and using the Service Connection as a variable, i.e. in the case of connecting to an Azure Container Registry:
Failed
pool:
vmImage: 'ubuntu-20.04'
variables:
dockerRegistryServiceConnection: 'my-service-connection'
baseContainerUrl: 'myregistry.azurecr.io/my_image:latest'
container:
image: $(baseContainerUrl)
endpoint: $(dockerRegistryServiceConnection)
Worked
pool:
vmImage: 'ubuntu-20.04'
variables:
baseContainerUrl: 'myregistry.azurecr.io/my_image:latest'
container:
image: $(baseContainerUrl)
endpoint: my-service-connection
In "classic release pipelines", a release is a snapshot of a release pipeline, with all the settings of the pipeline materialized, and a deployment is the execution of a pipeline stage in the release.
In our case, a release generating this error during deployment predated a service principal renewal. We could edit the release to use the new service principal and successfully deploy the modified release. The release pipeline did not need modifications.
Navigate to the release overview of the relevant release.
https://dev.azure.com/<user>/<project>/_releaseProgress?...
Select Edit > Edit release.
Click Edit tasks for the relevant stage.
Select the Azure App Service Deploy step.
Choose the correct Azure subscription and App Service name values.
These values will likely be the same as in the release pipeline
In our case these fields were empty and "needed attention".
Click Save.
Click Deploy.
The changes persist, so the corrected release can be deployed a second time without incident.
It is unclear whether this applies to YAML pipelines but I would guess no.
I was having this error because I was declaring the variable group containing the service connection name at stage level.
The error was fixed once I declared the variable group at pipeline level.
In my case, I was trying to use [AzureAppServiceSettings][1] task, and was using
azureSubscription with subscription id in the YAML file.
The YAML file
- task: AzureAppServiceSettings#1
displayName: Update App Settings of the Logic App
inputs:
azureSubscription: '$(azureSubscriptionId)'
resourceGroupName: ...
appName: ...
appSettings: ...
I got the same error and after clicking Authorise resources, I got error of no plan found for identifier xxxx.
Needed to change my YAML file to use connection name in Azure DevOps.
- task: AzureAppServiceSettings#1
displayName: Update App Settings of the Logic App
inputs:
azureSubscription: 'Nonprod Connection'
resourceGroupName: ...
appName: ...
appSettings: ...
So Nonprod Connection is one of my service connections in Azure Devops.
After fixing the value of azureSubscription, the pipeline doesn't show up the error anymore.
I had a similar problem and noticed that adding a task to run an Azure PowerShell script was also getting a similar error.
Turned out that the problem was solved when I verified the service connection twice within the project that was having the problem:

Publishing NuGet packages to Azure Artifacts from PR's

Can Azure Artifacts packages be made available publicly? If so, I'd like publish NuGet packages from a PR to my GitHub project. I currently get the following permissions error from PR builds:
[warning]Warning_SessionCreationFailed {"statusCode":500,"result":{"$id":"1","innerException":null,"message":"User
'89e4e6df-0ac0-471f-ba63-0270050c3b79' lacks permission to complete
this action. You need to have
'ReadPackages'.","typeName":"Microsoft.VisualStudio.Services.Feed.WebApi.FeedNeedsPermissionsException,
Microsoft.VisualStudio.Services.Feed.WebApi","typeKey":"FeedNeedsPermissionsException","errorCode":0,"eventId":3000}}
[error]Error: The process '/usr/bin/dotnet' failed with exit code 1
[error]Packages failed to publish
I'm using an azure-pipelines.yml file. Here is a link to my Azure Pipelines build.
Update 1
These are the users/groups I have already added to my feed:
These are the users/groups I can add to my feed, that I haven't already done:
Update 2
This is the yaml for the Azure Pipelines task I am using to publish the NuGet package:
- task: DotNetCoreCLI#2
displayName: 'Dotnet NuGet Push'
inputs:
command: push
nuGetFeedType: internal
packagesToPush: '/home/vsts/work/1/Windows/*.nupkg'
publishVstsFeed: schema-net
According to the error message, your account does not have permissions on that feed which you want to operate.
You need verify whether your account has Contributor or higher permissions on the feed which you are trying push to.
In another, the group Project Collection Build Service is a default Contributor. But also, as default setting, it does not include the account Project Collection Build Service(xxxx) as a member. So, if you are the owner, you may need to add the Project Collection Build Service(xxxx) account into Project Collection Build Service group.
Edit:
As I check your org info from our back end, I found the user(89e4e6df-0ac0-xxxxxx-0270050c3b79), which displayed in your error message, is a Service identity account. And it's domain is build. It's a special account, not the normal user who may create or trigger the pr. So, if you do not grant permission to this service identity account, it will not have permission to access the feed you want to push to.
And also, the direct parents groups of this security account in your Org is [org name]\Security Service Group. You can check it under your org setting. You can also check its permission under your feed.
So, for solved, you need to add this service identity account in to your feed setting, and grant it contributor or higher role.
2nd Update:
For clearly understand, let me clear up some details.
At first,according to the error message which displayed in log said lack ReadPackage permission, I considered this firstly with the permission of the feed which you wanted push to in task.
In addition, the user number which also displayed in the log, 89e4e6df-0ac0-xxxxxx-0270050c3b79. As I checked from backend, it is a VSID that represent a build service account: Schema.NET Build Service (schema-net). So, firstly, it’s easy to think that this account does not has relevant permission so that it could not push package.
But, after you update the feed setting, I check user VSID from backend again and review the error log. I figure it out. According to the logs of #20190625.1, you can see that the error begin occurred on getting source package:
##[warning]Can\'t find loc string for key:
Warning_SessionCreationFailed
Because of this error, it’s failed to create the correct package source package path so that the service account does not have permission to access it because it’s a wrong path:
In fact, the correct source package url should look like this( you can refer this from #2029062502)
https://pkgs.dev.azure.com/schema-net/_packaging/f43386ca-{package id}-d2f8da200fb3/nuget/v3/index.json
Now, I think this is a issue which about the configuration of your nuget.config file.

MyGet throwing repository URL is of an invalid format

I added a new build source on myget.org using VSTS, but MyGet is throwing this error:
The thing is, the URL shouldn't be incorrect... it was setup by MyGet itself, since I used the wizard.
What could be going on here?
You need to specify the authentication information.
Log on to your VSTS
Click your account > Security
Select Alternate authentication credentials (Personal access token is ok too)
Check enable alternate authentication credentials and create an alternate authentication credentials
Log on to your MyGet > Select Build Services > Click Edit to edit your build service
Type user name and password (if you are using Personal Access Token, the user name can be any, such as test, user etc…)
Start build