How can I use the Box Java SDK to create a shared link without specifying the share type? - box-api

In Box API v1, it was possible to request creation of a shared link for a file or folder, without caring about what kind of sharing was required. In fact, it was not possible to ask for a particular type of share - you just used the public_share method and passed in the target type (file/folder) and target ID, and optionally a share password. In an Enterprise Account, for instance, this might result in the maximum access level being "company" or "collaborators", if public links are disallowed.
With Box API v2, according to the docs here, you need to specify an access parameter that has to be "open", "company", or "collaborators".
The problem is, using the wrong type may cause the share to fail. For instance, in a folder/account that only allows collaborators, I get a 400 error if I ask for a "open" share.
What I really want is to get exactly the same result as if the user clicked the "Share" link in the Box web site. Which is, it should enable sharing for the file but default the level appropriately.
Is there a way to do this with v2, without the admin having to tell us their "preferred" access level for shared links we create? I'm using the Java SDK, like this:
BoxItemRequestObject req = BoxItemRequestObject.createSharedLinkRequestObject(BoxSharedLinkRequestObject.createSharedLinkRequestObject("open"));
BoxItem item = itemsManager.createSharedLink(<ID>, req, BoxResourceType.FILE);
Thanks,
Ben Gilbert
Smartsheet.com

Just set the access to the empty set {}
So your request would look like this:
{"shared_link": {}}

I figured out how to make this work. I need to set access to null when creating the BoxSharedLinkRequestObject, like this:**
BoxItemRequestObject req = BoxItemRequestObject.createSharedLinkRequestObject(BoxSharedLinkRequestObject.createSharedLinkRequestObject(null));
This doesn't produce quite the same JSON as was recommended (shared_link: {}), but it does produce JSON that is apparently equivalent: shared_link: { access: null }. I couldn't figure out any way to produce an empty shared_link object using the SDK -- I either had to have a null shared_link (which didn't work at all) or some value for the access field.

Related

Consul KV Store returns 403 on the parent folder of my key

I have a key in my KV store, let's say /global/test/my-key and I use a token that has the following policy :
key "/global/test/my-key" {
policy = "read"
}
Why, using the UI, I can access the URL http://localhost:8500/v1/kv/global/test/my-key/edit but I have a 403 on the following URLs http://localhost:8500/v1/kv/global/test and http://localhost:8500/v1/kv/global ?
Is there a way for me to access my key from the UI starting at the URL http://localhost:8500/v1/kv ?
NOTE: I have tried the "list" policy, but it gives read access to the other keys, which is not what I want.
EDIT: I just realized I had forgot to mention another condition that I am trying to meet. I have another key called for instance /global/secret/my-other-key and I don't want that key to be viewed from the UI nor the folder /global/secret/.
If you wish to have access to all of the mentioned paths, you should use this policy instead:
key_prefix "global" {
policy = "read"
}
This policy will give you access to global and any "sub-paths" of it.
Consul does not currently support performing recursive reads on paths where your token only has access to a subset of the keys under that parent path.
There's an open GitHub issue requesting this functionality be added https://github.com/hashicorp/consul/issues/4513. I recommend upvoting that issue to indicate your interest, and subscribe to it for updates so that you can track its progress.
If your particular use case is not accurately reflected in the initial description, feel free to leave a comment with additional information.

AWS SSM Parameter Store: How can I edit multi-line "SecureString" values using the console?

Currently, I use a single SSM parameter to store a set of properties separated by newlines, like this:
property1=value1
property2=value2
property3=value3
(I am aware of the 4K size limit, it's fine.)
This works well, for normal String type parameters that store non-sensitive information like environment configuration, but I'd also like to do similar for secrets using the SecureString parameter type.
The problem is that I can't edit the parameter value in the console because it's using a HTML input field of type="password" that doesn't handle newlines.
The multi-line value works fine with the actual parameter store backend - I can set a value with multiple lines with the SSM API no problem and they can be read with the EC2 CLI properly too.
But I can't edit them using the console. This is a problem because the whole point of using a SecureString parameter is that I intend the only place to edit/view these secrets to be via the console (so that permissions are controlled and access is audited).
There's a few infrastructure workarounds I could implement (one parameter for each secret, store the secrets on S3 or other secret storing service, etc.) but they all have drawbacks - I'm just trying to find out if there's a way around this using the console?
Is there any way I can work around this and use the console to edit multi-line SecureString parameters?
Any kind of browser workaround or hack that I might be able to use to tell the browser to use a textarea instead of a "password" type field?
I'm using Chrome, but I'd be happy to work around this by using another browser or something (editing the secrets is pretty rare, and viewing multi-line values in the console works fine).
EDIT
After posting this question, AWS notified me there was a whole new "AWS Systems Manager" UI, but it still has the same problem - I tried the below browser hacks on this new UI, but no luck.
Failed browser hack attempt 1: I tried opening the browser console, running document.getElementById("Value").value = "value1\nvalue2" and then clicking the save button, which set the value I injectec, but the newline was filtered out.
Failed browser hack attempt 2: I tried using the browser instpector to change the element to a TextArea and then typed in two lines of input and clicked save, but that didn't set the value at all.
From https://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html#cli-using-param-file, I learned you can pass a file as parameter to the --value argument. So if your file is called secrets.properties, you can do this:
aws ssm put-parameter --type SecureString --name secrets --value file://secrets.properties
I found a way to do it, but it's too much effort and too weird - if anyone can find a simpler way, I will mark that as the answer.
The hacky workaround is to install the "Tamper Chrome" extension + app, then capture the XHR request as the browser sends it and edit the new lines into the JSON.
Blech. Plus "Tamper Chrome" is pretty awful, I don't want to run it on my machine.
This might be better to use the new secrets manager that was launched recently. The interface for it is very close to parameter store but it has better support for multiple parameters in one place.
I wonder if the change in the console was due to the expected release of the service since they have a pricing model around secrets whereas parameter store is free
In the end, I decided the answer to this question is "don't do that". Not that I would've wanted to hear that when I was trying to make it work.
You should use a separate SSM param per secret for these reasons:
ability to grant permissions at fine grained level; e.g. you have an API password for calling your service, and a DB password for the service talk to a DB - if you store them in the same secret you couldn't only grant access to the API password.
ability to track key access separately - the SSM access logs can only tell you that the target machine/user accessed the SSM param at that time, it won't be able to tell you which secret was accessed
ability to use separate KMS keys to encrypt
Just watch out for the fact that you can only request a max of 10 SSM params at a time.
if you want, you can try with my app https://github.com/ledongthuc/awssecretsmanagerui
I try to create it to easier to update multi-line values and binary easier. Hope it's helpful with your case.

How to restrict fields returned by stackexchange api, and turn off paging?

I'd like to have a list of just the current titles for all questions in one of the smaller (less than 10,000 questions) stackexchange site. I tried the interactive utility here: https://api.stackexchange.com/docs/questions and it both reports the result as a json at the bottom, and produces the requesting url at the top. For example:
https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&tagged=apples&site=cooking
returns this JSON in my browser:
{"items":[{"tags":["apples","crumble"],"owner":{ ...
...
...],"has_more":true,"quota_max":300,"quota_remaining":252}
What is quota? It was 10,000 on one search on one site, but suddenly it's only 300 here.
I won't be doing this very often, what I'd like is the quickest way to edit that (or similar of course) url so I can get a list of all of the titles on a small site. I don't understand how to use paging, and I don't need any of the other fields. I don't care if I get them, but I'm thinking if I exclude them I can have more at once.
If I need to script it, python (2.7) is my preferred (only) language.
quota_max is the number of requests your application is allowed per day. 300 is the default for an unregistered application. This used to be mentioned directly on the page describing throttles, but seems to have been removed. Here is historical information describing the default.
To increase this to 10,000, you need to register an application and then authenticate by passing an access token in your script.
To get all titles on a site, you can use a Python library to help:
StackAPI. The answer below will use this library. DISCLAIMER: I wrote this library
Py-StackExchange
SEAPI
StackPy
Assuming you have registered your application and authenticated we can proceed.
First, install StackAPI (documentation):
pip install stackapi
This code will then grab the 10,000 most recent questions (max_pages * page_size) for the site hardwarerecs. Each page costs you one API hit, so the more items per page, the few API calls.
from stackapi import StackAPI
SITE = StackAPI('hardwarerecs')
SITE.page_size = 100
SITE.max_pages = 100
# Filter to only get question title and link
filter = '!BHMIbze0EQ*ved8LyoO6rNjkuLgHPR'
questions = SITE.fetch('questions', filter=filter)
In the questions variable is a dictionary that looks very similar to the API output, except that the library did all the paging for you. Your data is in questions['data'] and, in this case, contains a list of dictionaries that look like this:
[
...
{u'link': u'http://hardwarerecs.stackexchange.com/questions/29/sound-board-to-replace-a-gl2200-in-a-house-of-worship-foh-setting',
u'title': u'Sound board to replace a GL2200 in a house-of-worship FOH setting?'},
{ u'link': u'http://hardwarerecs.stackexchange.com/questions/31/passive-gps-tracker-logger',
u'title': u'Passive GPS tracker/logger'}
...
]
This result set is limited to only the title and the link because of the filter we applied. You can find the appropriate filter by adjusting what fields you want in the web UI and copying the filter field.
The hardwarerecs parameter that is passed when creating the SITE parameter is the first part of the site's domain URL. Alternatively, you can find it by looking at the api_site_parameter for your site when looking at the /sites end point.

Google Drive/OAuth - Can't figure out how to get re-usable GoogleCredentials

I've successfully installed and run the Google Drive Quick Start application called DriveCommandLine. I've also adapted it a little to GET file info for one of the files in my Drive account.
What I would like to do now is save the credentials somehow and re-use them without the user having to visit a web page each time to get an authorization code. I have checked out this page with instructions to Retrieve and Use OAuth 2.0 credentials. In order to use the example class (MyClass), I have modified the line in DriveCommandLine where the Credential object is instantiated:
Credential credential = MyClass.getCredentials(code, "");
This results in the following exception being thrown:
java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:187)
at com.google.api.client.json.jackson.JacksonFactory.createJsonParser(JacksonFactory.java:84)
at com.google.api.client.json.JsonFactory.fromInputStream(JsonFactory.java:247)
at com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.load(GoogleClientSecrets.java:168)
at googledrive.MyClass.getFlow(MyClass.java:145)
at googledrive.MyClass.exchangeCode(MyClass.java:166)
at googledrive.MyClass.getCredentials(MyClass.java:239)
at googledrive.DriveCommandLine.<init>(DriveCommandLine.java:56)
at googledrive.DriveCommandLine.main(DriveCommandLine.java:115)
I've been looking at these APIs (Google Drive and OAuth) for 2 days now and have made very little progress. I'd really appreciate some help with the above error and the problem of getting persistent credentials in general.
This whole structure seems unnecessarily complicated to me. Anybody care to explain why I can't just create a simple Credential object by passing in my Google username and password?
Thanks,
Brian O Carroll, Dublin, Ireland
* Update *
Ok, I've just gotten around the above error and now I have a new one.
The way I got around the first problem was by modifying MyClass.getFlow(). Instead of creating a GoogleClientServices object from a json file, I have used a different version of GoogleAuthorizationCodeFlow.Builder that allows you to enter the client ID and client secret directly as Strings:
flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, "<MY CLIENT ID>", "<MY CLIENT SECRET>", SCOPES).setAccessType("offline").setApprovalPrompt("force").build();
The problem I have now is that I get the following error when I try to use flow (GoogleAuthorizationCodeFlow object) to exchange the authorization code for the Credentials object:
An error occurred: com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "invalid_scope"
}
googledrive.MyClass$CodeExchangeException
at googledrive.MyClass.exchangeCode(MyClass.java:185)
at googledrive.MyClass.getCredentials(MyClass.java:262)
at googledrive.DriveCommandLine.<init>(DriveCommandLine.java:56)
at googledrive.DriveCommandLine.main(DriveCommandLine.java:115)
Is there some other scope I should be using for this? I am currently using the array of scopes provided with MyClass:
private static final List<String> SCOPES = Arrays.asList(
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile");
Thanks!
I feel your pain. I'm two months in and still getting surprised.
Some of my learnings...
When you request user permissions, specify "offline=true". This will ("sometimes" sic) return a refreshtoken, which is as good as a password with restricted permissions. You can store this and reuse it at any time (until the user revokes it) to fetch an access token.
My feeling is that the Google SDKs are more of a hinderence than a help. One by one, I've stopped using them and now call the REST API directly.
On your last point, you can (just) use the Google clientlogin protocol to access the previous generation of APIs. However this is totally deprecated and will shortly be turned off. OAuth is designed to give fine grained control of authorisation which is intrinsically complex. So although I agree it's complicated, I don't think it's unnecessarily so. We live in a complicated world :-)
Your and mine experiences show that the development community is still in need of a consolidated document and recipes to get this stuff into our rear-view mirrors so we can focus on the task at hand.
Oath2Scopes is imported as follows:
import com.google.api.services.oauth2.Oauth2Scopes;
You need to have the jar file 'google-api-services-oauth2-v2-rev15-1.8.0-beta.jar' in your class path to access that package. It can be downloaded here.
No, I don't know how to get Credentials without having to visit the authorization URL at least once and copy the code. I've modified MyClass to store and retrieve credentials from a database (in my case, it's a simple table that contains userid, accesstoken and refreshtoken). This way I only have to get the authorization code once and once I get the access/refresh tokens, I can reuse them to make a GoogleCredential object. Here's how Imake the GoogleCredential object:
GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory)
.setTransport(httpTransport).setClientSecrets(clientid, clientsecret).build();
credential.setAccessToken(accessToken);
credential.setRefreshToken(refreshToken);
Just enter your clientid, clientsecret, accessToken and refreshToken above.
I don't really have a whole lot of time to separate and tidy up my entire code to post it up here but if you're still having problems, let me know and I'll see what I can do. Although, you are effectively asking a blind man for directions. My understanding of this whole system is very sketchy!
Cheers,
Brian
Ok, I've finally solved the second problem above and I'm finally getting a working GoogleCredential object with an access token and a refresh token.
I kept trying to solve the scopes problem by modifying the list of scopes in MyClass (the one that manages credentials). In the end I needed to adjust the scopes in my modified version of DriveCommandLine (the one that's originally used to get an authorization code). I added 2 scopes from Oauth2Scopes:
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
Arrays.asList(DriveScopes.DRIVE, Oauth2Scopes.USERINFO_EMAIL, Oauth2Scopes.USERINFO_PROFILE))
.setAccessType("offline").setApprovalPrompt("force").build();
Adding the scopes for user information allowed me to get the userid later in MyClass. I can now use the userid to store the credentials in a database for re-use (without having to get the user to go to a URL each time). I also set the access type to "offline" as suggested by pinoyyid.

Anonymous users with sitecore domains

I'm checking if this is a sitecore bug, or if I'm missing something obvious.
EDIT FOR CLARIFICATION: The problem I'm having is that I'm trying to set up the configuration settings in the Domains.config file so that Sitecore shouldn't be creating (and/or returning) an anonymous user for a domain set up this way. However, if I use the Domain.GetUsers() function on the domain, I still get the anonymous user returned.
The membership provider is a custom built and connects to LDAP in read only mode.
Details
Using Sitecore 6.4.1 and given the following domain configuration in App_Config/Security/domains.config
<domain name="DOMAINNAME" ensureAnonymousUser="false" anonymousUserName="" everyoneRoleName="" />
and these comments in that domain.config file
anonymousUserName: <snip> Set to blank to disable the anonymous user for the domain. Optional
ensureAnonymousUser: Indicates if the domain should ensure that an anonymous user for the domain exists in the Membership database. Optional - default value: false
everyoneRoleName: <snip> Set to blank to disable the everyone role for the domain. Optional - default value: Everyone
If I use the following code,
List<Sitecore.Security.Accounts.User> users = new List<Sitecore.Security.Accounts.User>();
var domain = Sitecore.Security.Domains.Domain.GetDomain(DOMAINNAME);
users.AddRange(domain.GetUsers().ToArray<Sitecore.Security.Accounts.User>());
I get the anonymous user included in users list. I assumed from the comments in the domain.config file that I shouldn't get the anonymous user if I set up my domain as above.
Is there something obvious that I'm missing?
Just a guess as I have not used 6.4 yet or tweaked any of those types of setting before... but I believe Sitecore always comes pre-packaged with the Anonymous user in the membership. By setting ensureAnonymousUser to false you're just telling it not to ensure its there, but its already there by default. Why don't you try this test:
Set ensureAnonymousUser to true then delete [*] the Anonymous user from the user manager.
Log out and back in and see if it's there again. If so then the "ensure" aspect of that worked. So...
Set ensureAnonymousUser to false then do the same thing. Does the user come back?
This is really just a hunch on how it works -- I don't have an environment like that setup right now to play with, but its worth a shot.
[*] - to delete a user form the User Manager, go to Sitecore > Security > User Manager
I think it's more question to membership provider you use. Take a look at Active Directory Module
Maybe this is something that could help you.