Add AWS SQS Permission to all Principals through SDK - java

I'm trying to create an AWS SQS queue through the Java SDK, and then add all permissions for all users. I can create the queue fine, but I'm struggling to know what value I can pass in for the Principals. This is what my code looks like:
CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName).withAttributes(attributes);
CreateQueueResult createQueueResult = amazonSqs.createQueue(createQueueRequest);
String queueUrl = createQueueResult.getQueueUrl();
amazonSqs.addPermission(queueUrl, "*", ????, Arrays.asList("*"));
The ??? is what I'm not sure on. I've tried Arrays.asList("*") but it complains about it not being valid. In the web console, there is a checkbox for Everyone, and I'm just wanting to do the same thing in the SDK. Is there some value I can pass for this?
--- UPDATE ---
I've been able to accomplish this another way through a Policy:
String queueUrl = createQueueResult.getQueueUrl();
GetQueueAttributesResult getQueueAttributesResult = amazonSqs.getQueueAttributes(queueUrl, Arrays.asList(QUEUE_ARN_ATTRIBUTE_NAME));
String queueArn = getQueueAttributesResult.getAttributes().get(QUEUE_ARN_ATTRIBUTE_NAME);
if (needToSetPolicy)
{
Policy allAccessPolicy = new Policy("SQSAllAccess", Arrays.asList(
new Statement(Effect.Allow)
.withActions(() -> "SQS:*")
.withPrincipals(Principal.All)
.withId("SQSAllAccessStatement")
.withResources(new Resource(queueArn))
));
Map<String, String> policyMap = new HashMap<>(1);
policyMap.put(POLICY_ATTRIBUTE_NAME, allAccessPolicy.toJson());
amazonSqs.setQueueAttributes(queueUrl, policyMap);
}
It seems like there should be a better/easier way to do this. Are there any better/cleaner/easier ways of doing this?

In kotlin using the constants from the SDK
val policy: Policy = Policy("AllowAllSendMessage", listOf(Statement(Effect.Allow)
.withActions(SQSActions.SendMessage)
.withPrincipals(Principal.All)
.withId("AllowAllSendMessage")
.withResources(Resource(queueArn))))
_sqs.setQueueAttributes(SetQueueAttributesRequest()
.withQueueUrl(queueUrl)
.withAttributes(mapOf(QueueAttributeName.Policy.toString() to policy.toJson())))

Related

Is it possible to create guest users using Java SDK graph api?

I am using this code to create users in Azure Active Directory from Java SDK. I have installed all required packages and libraries.
User user = new User();
user.accountEnabled = true;
user.displayName = "Kevin";
user.mailNickname = "kevin";
user.userPrincipalName = "kevin234#domain.onmicrosoft.com";
PasswordProfile passwordProfile = new PasswordProfile();
passwordProfile.forceChangePasswordNextSignIn = true;
passwordProfile.password = "***********";
user.passwordProfile = passwordProfile;
graphClient.users()
.buildRequest()
.post(user);
I can create normal users but how to create guest users. I included user.userType='guest' in the above code
user.userPrincipalName = "kevin234#hotmail.com";
user.userType='guest'; // I added this that outputs Invalid Request error
graphClient.users()
.buildRequest()
.post(user);
Is there any easy way to do that using Graph API query? Can somebody suggest the changes I have to do in my code to achieve my scenario?
TIA
I tried to reproduce the same in my environment and got the below results:
To create guest users, you can make use of below query:
POST https://graph.microsoft.com/v1.0/invitations
Content-type: application/json
{
"invitedUserEmailAddress": "kevin234#hotmail.com",
"inviteRedirectUrl": "https://yourwebsite.com"
}
Response:
When I checked the Portal, guest user created successfully like below:
You can find the code snippet in Java beside your query response like below:
Code Sample in Java:
GraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();
Invitation invitation = new Invitation();
invitation.invitedUserEmailAddress = "kevin234#hotmail.com";
invitation.inviteRedirectUrl = "https://yourwebsite.com";
graphClient.invitations()
.buildRequest()
.post(invitation);
Credits: Create invitation - Microsoft Docs

How do I specify the licensing query parameter for the Microsoft Teams API when using the Microsoft Graph SDK for Java?

According to the Licensing and payment requirements for the Microsoft Teams API documentation, I need to include a model query parameter to specify the
licensing and payment model for the Microsoft Teams API. How do I do this when using the Microsoft Graph SDK for Java?
I currently access the Graph API using the com.microsoft.graph.requests.GraphServiceClient class:
public static GraphServiceClient<Request> getGraphClient(#NonNull final AadAuthenticationProperties properties,
#NonNull final String tenantId) {
var credential = new ClientSecretCredentialBuilder().clientId(properties.getCredential().getClientId())
.clientSecret(properties.getCredential().getClientSecret())
.tenantId(tenantId)
.build();
var authProvider = new TokenCredentialAuthProvider(
properties.getAuthorizationClients().get("graph").getScopes(), credential);
final var logger = new DefaultLogger();
logger.setLoggingLevel(LoggerLevel.DEBUG);
return GraphServiceClient.builder().authenticationProvider(authProvider).logger(logger).buildClient();
}
Is there someway that I should alter this client? Would this only be necessary for subscribing to change notifications? While for querying for all object details? While querying for certain particular object details?
Code Snippet that might help, the following is for getAllMessages model A.
You can modify it as per your needs but the underlying logic remains the same.
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var queryOptions = new List<QueryOption>()
{
new QueryOption("model", "A")
};
var getAllMessages = await graphClient.Users["Alexw#cqons.onMicrosoft.com"].Chats
.GetAllMessages()
.Request( queryOptions )
.GetAsync();
For all future readers, you can query this in Graph Explorer and go to the code snippet section to get the corresponding code snippet.

How to use UpdateEventSourceMappingRequest in java?

I'm trying to use something like this:
UpdateEventSourceMappingRequest request = new UpdateEventSourceMappingRequest()
.withFunctionName("arn:aws:lambda:us-east-1:9999999999:function:"+functionName)
.withEnabled(false);
But I received a error because I have to use .withUUID(uuid):
UpdateEventSourceMappingRequest request = new UpdateEventSourceMappingRequest()
.withUUID(uuid))
.withFunctionName("arn:aws:lambda:us-east-1:9999999999:function:"+functionName)
.withEnabled(false);
I don't know how to get the value of uuid ( uuid from aws lambda ).
Can you help me with the solution to my problem ?
You need to provide the UUID identifier of the event source mapping to update it (and this field is mandatory). Update-request is not intended to create it.
When you create an event source mapping (here) - aws should return a response with a UUID identifier which you then may use in the update request.
That's the solution that I founded:
String strUUID = "";
ListEventSourceMappingsRequest requestList = new ListEventSourceMappingsRequest()
.withEventSourceArn("arn:aws:sqs:us-east-1:9999999999:test");
ListEventSourceMappingsResult result = awsLambda.listEventSourceMappings(requestList);
List<EventSourceMappingConfiguration> eventSourceMappings = result.getEventSourceMappings();
for (EventSourceMappingConfiguration eventLambda : eventSourceMappings) {
strUUID = eventLambda.getUUID();
}
System.out.println("Output UUID " + strUUID);
We have to use the ARN of the SQS that's trigger of the aws lambda.

Find all the attached volumes for an EC2 instance

I'm using the below code to get all the available volumes under EC2. But I can't find any Ec2 api to get already attached volumes with an instance. Please let me know how to get all attached volumes using instanceId.
EC2Api ec2Api = computeServiceContext.unwrapApi(EC2Api.class);
List<String> volumeLists = new ArrayList<String>();
if (null != volumeId) {
volumeLists.add(volumeId);
}
String[] volumeIds = volumeLists.toArray(new String[0]);
LOG.info("the volume IDs got from user is ::"+ Arrays.toString(volumeIds));
Set<Volume> ec2Volumes = ec2Api.getElasticBlockStoreApi().get()
.describeVolumesInRegion(region, volumeIds);
Set<Volume> availableVolumes = Sets.newHashSet();
for (Volume volume : ec2Volumes) {
if (volume.getSnapshotId() == null
&& volume.getStatus() == Volume.Status.AVAILABLE) {
LOG.debug("available volume with no snapshots ::" + volume.getId());
availableVolumes.add(volume);
}
}
The AWS Java SDK now provides a method to get all the block device mappings for an instance. You can use that to get a list of all the attached volumes:
// First get the EC2 instance from the id
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest().withInstanceIds(instanceId);
DescribeInstancesResult describeInstancesResult = ec2.describeInstances(describeInstancesRequest);
Instance instance = describeInstancesResult.getReservations().get(0).getInstances().get(0);
// Then get the mappings
List<InstanceBlockDeviceMapping> mappingList = instance.getBlockDeviceMappings();
for(InstanceBlockDeviceMapping mapping: mappingList) {
System.out.println(mapping.getEbs().getVolumeId());
}
You can filter the output of the EC2 DescribeVolumes API call. There are various attachment.* filters available, the one you want is filtering by attached instance ID. Try the following code:
Multimap<String, String> filter = ArrayListMultimap.create();
filter.put("attachment.instance-id", instanceId);
filter.put("attachment.status", "attached");
Set<Volume> volumes = ec2Api.getElasticBlockStoreApi().get()
.describeVolumesInRegionWithFilter(region, volumeIds, filter);
The filter is a Multimap with the keys and values you want to filter on. You can actually specify the same filter multiple times, for example to get all volumes attached to a number of different instances.
You can use volumeAttachmentApi.listAttachmentsOnServer() to do this.
NovaApi novaApi = context.unwrapApi(NovaApi.class);VolumeApi volumeApi = novaApi.getVolumeExtensionForZone(region).get();
VolumeAttachmentApi volumeAttachmentApi = novaApi.getVolumeAttachmentExtensionForZone(region).get();
volumeAttachmentApi.listAttachmentsOnServer(serverId)

Getting all ActiveDirectory groups using OpenSSO Client SDK

I hope someone here has experience with Sun OpenSSO (now ForgeRock OpenAM).
I'm trying to get all groups in ActiveDirectory using the OpenSSO Client SDK in Java / JBoss EAP 5.0.
I tried the following by combining various samples and code snippets I could find on the web, but this fails and eventually logs "Memberships for identities other than Users is not allowed." The basic approach was to use AMIdentityRepository -> getRealmIdentity() -> getMemberships(IdType.GROUP) :
SSOTokenManager manager = SSOTokenManager.getInstance();
String tokenString = URLDecoder.decode(tokenID, "ISO-8859-1");
SSOToken token = manager.createSSOToken(tokenString);
if (manager.isValidToken(token)) {
SSOToken adminToken = (SSOToken)AccessController.
doPrivileged(AdminTokenAction.getInstance());
AMIdentityRepository rep = new AMIdentityRepository(adminToken, "/");
AMIdentity identity = rep.getRealmIdentity();
Set groups = identity.getMemberships(IdType.GROUP);
}
Note I'm not trying to determine if a user is a member of a group or to retrieve a user's groups - I'm trying to get a list of ALL groups.
Any suggestions would be appreciated - thanks!
Instead of rep.getRealmIdentity() and then calling getMemberships(IdType.GROUP), use searchIdentities and getSearchResults like:
SSOToken token = (SSOToken) AccessController.doPrivileged(AdminTokenAction.getInstance());
AMIdentityRepository ir = new AMIdentityRepository(token, "/");
IdSearchResults results = ir.searchIdentities(IdType.GROUP, "*", new IdSearchControl());
Set<AMIdentity> groups = results.getSearchResults();
for (AMIdentity group : groups) {
logger.debug("Group Name : " + group.getName());
}

Categories

Resources