Can't pass password from credentialsJSON to commitStatusPublisher (bitbucket server) Teamcity - token

It seems that i have an old version of commitStatusPublisher plugin and it can't convert credentialsJSON string to its value. In any other situation I can access password with
params.findRawParam("env.mypass")!!.value
or in buildstep, script content
$mypass
But commitStatusPublisher not working with it.
Code example
import jetbrains.buildServer.configs.kotlin.v2019_2.*
import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.commitStatusPublisher
params {
password("env.mypass", "credentialsJSON:8420d5dc-1d32-4f9e-a74d-c9444be05c23", display = ParameterDisplay.HIDDEN)
}
features {
commitStatusPublisher {
publisher = bitbucketServer {
url = "https://bitbucket.domain.com/"
userName = "user"
password = params.findRawParam("env.mypass")!!.value
}
}
}
Maybe I can somehow extract 'raw' var to use it for that plugin?
for example
var pass = something("env.mypass")
features {
commitStatusPublisher {
publisher = bitbucketServer {
url = "https://bitbucket.domain.com/"
userName = "user"
password = pass
}
}
}
In the result i want to keep password in TC tokens and use it with my version of commitStatusPublisher

Seems like a bug.
Recreating the token resolves problem

Related

How to map the Groovy script to Nexus script API and pass the Argument in JSON

I have a script which will add the nexus role to the LDAP user.
import org.sonatype.nexus.security.role.RoleIdentifier;
import org.sonatype.nexus.security.user.User;
import org.sonatype.nexus.security.user.UserManager;
String userId = 'NA12345';
String newRoleId = 'dot-maven'
String realm = 'LDAP'
String role_realm = 'default'
User user = security.securitySystem.getUser(userId, realm)
authManager = security.getSecuritySystem().getAuthorizationManager(UserManager.DEFAULT_SOURCE)
def existingRole = authManager.getRole(newRoleId)
if(user != null) {
RoleIdentifier newRole = new RoleIdentifier(role_realm, existingRole.roleId);
user.addRole(newRole)
security.securitySystem.setUsersRoles(user.getUserId(), realm, user.getRoles());
} else {
log.warn("No user with ID of $userId found.")
}
Now I need to add this script in the NExus Script API and pass the username and role id as argrument in JSON format.
How can i achieve this?

Cannot store Certificate to KeyChain using SecKeyChain in Xamarin

After hours spent reading through what's available online to fix this, I decided to post my question here.
My goal is simple: Store an X509Certficate to KeyChain using Xamarin for iOS. This is a self signed certificate that I generated using BouncyCastle library.
I'm successfuly importing it, but when saving to KeyChain using SecKeyChain.Add, the result is always SecStatusCode.Paramwhich the documentation explains is missing or invalid parameter. Here's the method I use
public static bool StoreCertInKeyChain(X509Certificate2 certificate, string password)
{
var data = certificate.Export(X509ContentType.Pkcs12, password);
var options = NSMutableDictionary.FromObjectAndKey(FromObject(password), SecImportExport.Passphrase);
var statusCode = SecImportExport.ImportPkcs12(data, options, out NSDictionary[] result);
if (statusCode != SecStatusCode.Success) return false;
var certChain = result[0][SecImportExport.CertChain];
var record = new SecRecord(SecKind.Certificate)
{
Label = "MyKey",
Account = "Certificate",
ApplicationTag = "MyTag"
};
record.SetValueRef(certChain);
// Using the below code instead, produces the same result
// var cert = new SecCertificate(certChain.Handle);
// record.SetValueRef(cert);
var resultAdd = SecKeyChain.Add(record);
return resultAdd == SecStatusCode.Success;
}
Has anyone ran into this problem? I'm out of ideas what else to try. I followed the examples given on Xamarin documentation site, without success. Thank you
Answering my solution here, in case anyone else runs into the same issue. The problem was that the certificate supplied in the SecRecord wasn't an instance of SecCertificate, so using SecImportExport.ImportPkcs12 was the wrong way to do it. I ended up using SecIdentity.Import instead, which gives a reference to the certificate as well as the private key in it. The certificate and the private key need to be added to key chain separately using an identity. Here's the code that accomplishes this.
var identity = SecIdentity.Import(certificate.Export(X509ContentType.Pkcs12, password), password);
var storedCertificate = SecKeyChain.QueryAsConcreteType(new SecRecord(SecKind.Certificate) { Label = "My Cert" }, out SecStatusCode statusCode);
if (statusCode != SecStatusCode.Success)
{
var record = new SecRecord(SecKind.Certificate);
record.Label = "My Cert";
record.SetValueRef(identity.Certificate);
var result = SecKeyChain.Add(record);
SecKeyChain.AddIdentity(identity);
storedCertificate = SecKeyChain.QueryAsConcreteType(new SecRecord(SecKind.Certificate) { Label = "My Cert" }, out statusCode);
}
var storedIdentity = SecKeyChain.FindIdentity(storedCertificate as SecCertificate);
The certificate can be retrieved using the label, but to get the private key, the identity must be queried using the certificate as parameter in SecKeyChain.FindIdentity. From this point on, access to signing and decryption on the private key is available from the identity instance.

Grails2.1 Dynamic mail configuration

I am trying to send an email from a grails app. I tried with recommended settings using gmail and it worked fine. I sent mail successfully. But I want to override the username and password dynamically. I don't know how can I do it. Can anybody help?
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "faruq#gmail.com" // Want to change dynamically like variable ${branch.mail}
password = "12345" // Want to change dynamically like variable ${branch.pass}
props = [
"mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"
]
}
}
I use this process for overriding the username from the controller
grailsApplication.config.grails.mail.username = Branch.get(2).mail
by this process username successfully changes
here Branch is my domain class and mail is property
but an authentication problem comes up:
javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted
Now what can I do?
You can use an external configuration file - put placeholder values in the main Config.groovy
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "<changeme>"
password = "<changeme>"
props = [
"mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"
]
}
}
and then override them with the correct values in the external config:
grails {
mail {
username = "faruq#gmail.com"
password = "12345"
}
}
To be able to change the credentials dynamically at run time it gets rather more complicated. Under the covers the mail plugin creates a Spring bean which is an instance of JavaMailSenderImpl to handle the actual sending of emails, and this bean is configured by default with static settings from the config. But at runtime this class appears to call its own getUsername() and getPassword() every time it needs to send a message. So you could replace this bean with your own custom subclass of JavaMailSenderImpl that overrides these methods to pull the details from the request context (code example, not tested, and imports/error handling omitted):
src/groovy/com/example/RequestCredentialsMailSender.groovy
class RequestCredentialsMailSender extends JavaMailSenderImpl {
public String getUsername() {
return RequestContextHolder.requestAttributes?.currentRequest?.mailUsername ?: super.getUsername()
}
public String getPassword() {
return RequestContextHolder.requestAttributes?.currentRequest?.mailPassword ?: super.getPassword()
}
}
You'd have to register this bean in your resources.groovy, and duplicate a fair bit of the configuration from the mail plugin itself, which is less than ideal:
grails-app/conf/spring/resources.groovy
beans = {
mailSender(com.example.RequestCredentialsMailSender) {
def mailConf = application.config.grails.mail
host = mailConf.host
port = mailConf.port
username = mailConf.username // the default, if not set in request
password = mailConf.password
protocol = mailConf.protocol
javaMailProperties = mailConf.props
}
}
Now when you need to send mail from a controller you can do
request.mailUsername = Branch.get(2).mail
request.mailPassword = Branch.get(2).mailPassword
sendMail { ... }
Just wanted to verify Ian's answer and expand it.
In the default Config.groovy file I have the added external config line:
grails.config.locations = [
"file:./${appName}-config.groovy",
"classpath:${appName}-config.groovy"
]
....
// and here is the mail config as above
grails{
mail{
....
In the config file at the root level I have my config file: TestApp-config.groovy (where TestApp is the name of my app) as above:
grails {
mail {
username = "faruq#gmail.com"
password = "12345"
}
}
Didn't need anything past this and it worked great.
We can also use replyTo field if our aim is only to get the reply back on specific Email Id. We can dynamically pass an email id to "replyTo" field and can expect an email back on the same.
Example :
asynchronousMailService.sendMail
{
to ["xyz#gmail.com","pqr#gmail.com"]
subject "Subject Text"
if(ccs) cc ["xyz1#gmail.com","pqr1#gmail.com"]
if(bccs) bcc ["xyz2#gmail.com","pqr2#gmail.com"]
if(replyTo) replyTo "xyz#gmail.com"
if(attachBytes) attachBytes attachBytes
}
NOTE: Adding "replyTo" will only allow us to get the emails back on the specified email-id and will not send the email from the configured email.
It was suitable in my use case. Hope it helps !

How can one supply credentials during a Fetch call?

We're not talking about SSH since it's not yet implemented, but how can I supply credentials for the repository before I perform a fetch via HTTP/HTTPS? There doesn't seem to be a parameter for a Credentials instance, and nothing when constructing a Repository instance for storing credentials.
Within the FetchFixture.cs file, there is a Fetch() test using credentials:
[SkippableFact]
public void CanFetchIntoAnEmptyRepositoryWithCredentials()
{
InconclusiveIf(() => string.IsNullOrEmpty(Constants.PrivateRepoUrl),
"Populate Constants.PrivateRepo* to run this test");
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
Remote remote = repo.Network.Remotes.Add(remoteName, Constants.PrivateRepoUrl);
// Perform the actual fetch
repo.Network.Fetch(remote, new FetchOptions
{
Credentials = new Credentials
{
Username = Constants.PrivateRepoUsername,
Password = Constants.PrivateRepoPassword
}
});
}
}

How to check whether user is following me not using TweetSharp.TwitterService.ListFollowers()

Is there some function in TweetSharp that could be used in a similar way to my 'IsFollowingMe' below?
I'd like to check whether a user is following me before I attempt to send some private message.
TweetSharp.TwitterService service;
string screenName = "#some_one";
string someMessage = "Some Message";
if (service.IsFollowingMe(screenName))
{
service.SendDirectMessage(screenName, someMessage);
else
NotifyThatSendingNotPossible();
}
First option to such approach is to use:
TweetSharp.TwitterService service;
TwitterCursorList<TwitterUser> followers = service.ListFollowers();
and then iterate through the result to find out if user is following my account. But this will eventually be ineffective when there are a lot of followers.
Another option is to execute service.SendDirectMessage and then check if the result is null or not. I tested such approach with success - however my application logic prefers to check in advance if sending is possible and based on this information should do different actions.
The answer is as follows:
TweetSharp.TwitterService service;
string fromUser = "#mr_sender";
string toUser = "#some_one";
string someMessage = "Some Message";
TweetSharp.TwitterFriendship friendship =
service.GetFriendshipInfo(fromUser, toUser);
if (friendship.Relationship.Source.CanDirectMessage.HasValue &&
friendship.Relationship.Source.CanDirectMessage.Value)
{
service.SendDirectMessage(screenName, someMessage);
}
else
{
NotifyThatSendingNotPossible();
}
I could able to solve this using below way.
var twitterFriendship = service.GetFriendshipInfo(new GetFriendshipInfoOptions() { SourceScreenName = "source_name", TargetScreenName = "target_name"});
After that, you can check like below
if(twitterFriendship.Relationship.Source.Following && twitterFriendship.Relationship.Target.FollowedBy)
{
service.SendDirectMessage(new SendDirectMessageOptions() { ScreenName="target_name",Text="message"})
}

Resources