com.microsoft.azure.storage.StorageCredentialsSharedAccessSignature Java Examples

The following examples show how to use com.microsoft.azure.storage.StorageCredentialsSharedAccessSignature. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CloudBlobContainerTests.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
@Test
@Category({ DevFabricTests.class, DevStoreTests.class })
public void testCloudBlobContainerReferenceFromServerSAS() throws StorageException, URISyntaxException,
        IOException, InvalidKeyException {
    this.container.create();
    CloudBlob blob = BlobTestHelper.uploadNewBlob(this.container, BlobType.BLOCK_BLOB, null, 1024, null);

    SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
    Calendar now = Calendar.getInstance();
    now.add(Calendar.MINUTE, 10);
    policy.setSharedAccessExpiryTime(now.getTime());
    policy.setPermissions(EnumSet.of(SharedAccessBlobPermissions.READ));
    String token = this.container.generateSharedAccessSignature(policy, null);

    CloudBlobContainer containerSAS = new CloudBlobContainer(this.container.getStorageUri(),
            new StorageCredentialsSharedAccessSignature(token));
    CloudBlob blobRef = containerSAS.getBlobReferenceFromServer(blob.getName());
    assertEquals(blob.getClass(), blobRef.getClass());
    assertEquals(blob.getUri(), blobRef.getUri());
}
 
Example #2
Source File: TableTests.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
private static void testIsUsePathStyleUri(StorageCredentials creds, String tableEndpoint, boolean usePathStyleUris)
        throws URISyntaxException, InvalidKeyException, StorageException {
    CloudTableClient tableClient = new CloudTableClient(new URI(tableEndpoint), creds);
    assertEquals(usePathStyleUris, tableClient.isUsePathStyleUris());

    CloudTable table = tableClient.getTableReference("mytable");
    assertEquals(tableEndpoint + "/mytable", table.getUri().toString());

    String sasToken = table.generateSharedAccessSignature(null, "fakeIdentifier", null, null, null, null);
    tableClient = new CloudTableClient(new URI(tableEndpoint),
            new StorageCredentialsSharedAccessSignature(sasToken));
    assertEquals(usePathStyleUris, tableClient.isUsePathStyleUris());

    table = new CloudTable(table.getUri(), tableClient.getCredentials());
    assertEquals(tableEndpoint + "/mytable", table.getUri().toString());
}
 
Example #3
Source File: AzureNativeFileSystemStore.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to Azure storage using shared access signature credentials.
 */
private void connectUsingSASCredentials(final String accountName,
    final String containerName, final String sas) throws InvalidKeyException,
    StorageException, IOException, URISyntaxException {
  StorageCredentials credentials = new StorageCredentialsSharedAccessSignature(
      sas);
  connectingUsingSAS = true;
  connectUsingCredentials(accountName, credentials, containerName);
}
 
Example #4
Source File: CloudQueue.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the passed in URI. Then parses it and uses its components to populate this resource's properties.
 * 
 * @param completeUri
 *            A {@link StorageUri} object which represents the complete URI.
 * @param credentials
 *            A {@link StorageCredentials} object used to authenticate access.
 * @throws StorageException
 *             If a storage service error occurred.
 */
private void parseQueryAndVerify(final StorageUri completeUri, final StorageCredentials credentials) 
        throws StorageException {
    Utility.assertNotNull("completeUri", completeUri);

    if (!completeUri.isAbsolute()) {
        throw new IllegalArgumentException(String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()));
    }

    this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri);
    
    final StorageCredentialsSharedAccessSignature parsedCredentials = 
            SharedAccessSignatureHelper.parseQuery(completeUri);

    if (credentials != null && parsedCredentials != null) {
        throw new IllegalArgumentException(SR.MULTIPLE_CREDENTIALS_PROVIDED);
    }

    try {
        final boolean usePathStyleUris = Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri());
        this.queueServiceClient = new CloudQueueClient(PathUtility.getServiceClientBaseAddress(
                this.getStorageUri(), usePathStyleUris), credentials != null ? credentials : parsedCredentials);
        this.name = PathUtility.getContainerNameFromUri(storageUri.getPrimaryUri(), usePathStyleUris);
    }
    catch (final URISyntaxException e) {
        throw Utility.generateNewUnexpectedStorageException(e);
    }
}
 
Example #5
Source File: CloudTable.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the passed in URI. Then parses it and uses its components to populate this resource's properties.
 * 
 * @param completeUri
 *            A {@link StorageUri} object which represents the complete URI.
 * @param credentials
 *            A {@link StorageCredentials} object used to authenticate access.
 * @throws StorageException
 *             If a storage service error occurred.
 */  
private void parseQueryAndVerify(final StorageUri completeUri, final StorageCredentials credentials) 
        throws StorageException {
    Utility.assertNotNull("completeUri", completeUri);

    if (!completeUri.isAbsolute()) {
        throw new IllegalArgumentException(String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()));
    }

    this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri);
    
    final StorageCredentialsSharedAccessSignature parsedCredentials = 
            SharedAccessSignatureHelper.parseQuery(completeUri);

    if (credentials != null && parsedCredentials != null) {
        throw new IllegalArgumentException(SR.MULTIPLE_CREDENTIALS_PROVIDED);
    }

    try {
        final boolean usePathStyleUris = Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri());
        this.tableServiceClient = new CloudTableClient(PathUtility.getServiceClientBaseAddress(
                this.getStorageUri(), usePathStyleUris), credentials != null ? credentials : parsedCredentials);
        this.name = PathUtility.getTableNameFromUri(storageUri.getPrimaryUri(), usePathStyleUris);
    }
    catch (final URISyntaxException e) {
        throw Utility.generateNewUnexpectedStorageException(e);
    }
}
 
Example #6
Source File: CloudFile.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the passed in URI. Then parses it and uses its components to populate this resource's properties.
 * 
 * @param completeUri
 *            A {@link StorageUri} object which represents the complete URI.
 * @param credentials
 *            A {@link StorageCredentials} object used to authenticate access.
 * @throws StorageException
 *             If a storage service error occurred.
 * @throws URISyntaxException 
 */
private void parseQueryAndVerify(final StorageUri completeUri, final StorageCredentials credentials)
        throws StorageException, URISyntaxException {
   Utility.assertNotNull("completeUri", completeUri);

    if (!completeUri.isAbsolute()) {
        throw new IllegalArgumentException(String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()));
    }

    this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri);
    
    final StorageCredentialsSharedAccessSignature parsedCredentials = 
            SharedAccessSignatureHelper.parseQuery(completeUri);

    if (credentials != null && parsedCredentials != null) {
        throw new IllegalArgumentException(SR.MULTIPLE_CREDENTIALS_PROVIDED);
    }

    try {
        final boolean usePathStyleUris = Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri());
        this.fileServiceClient = new CloudFileClient(PathUtility.getServiceClientBaseAddress(
                this.getStorageUri(), usePathStyleUris), credentials != null ? credentials : parsedCredentials);
        this.name = PathUtility.getFileNameFromURI(this.storageUri.getPrimaryUri(), usePathStyleUris);
    }
    catch (final URISyntaxException e) {
        throw Utility.generateNewUnexpectedStorageException(e);
    }

    final HashMap<String, String[]> queryParameters = PathUtility.parseQueryString(completeUri.getQuery());

    final String[] snapshotIDs = queryParameters.get(Constants.QueryConstants.SHARE_SNAPSHOT);
    if (snapshotIDs != null && snapshotIDs.length > 0) {
        this.getShare().snapshotID = snapshotIDs[0];
    }
}
 
Example #7
Source File: CloudFileShare.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the passed in URI. Then parses it and uses its components to populate this resource's properties.
 * 
 * @param completeUri
 *            A {@link StorageUri} object which represents the complete URI.
 * @param credentials
 *            A {@link StorageCredentials} object used to authenticate access.
 * @throws StorageException
 *             If a storage service error occurred.
 */
private void parseQueryAndVerify(final StorageUri completeUri, final StorageCredentials credentials)
        throws StorageException {
   Utility.assertNotNull("completeUri", completeUri);

    if (!completeUri.isAbsolute()) {
        throw new IllegalArgumentException(String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()));
    }

    this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri);

    final HashMap<String, String[]> queryParameters = PathUtility.parseQueryString(completeUri.getQuery());

    final String[] snapshotIDs = queryParameters.get(Constants.QueryConstants.SHARE_SNAPSHOT);
    if (snapshotIDs != null && snapshotIDs.length > 0) {
        this.snapshotID = snapshotIDs[0];
    }

    final StorageCredentialsSharedAccessSignature parsedCredentials = 
            SharedAccessSignatureHelper.parseQuery(completeUri);

    if (credentials != null && parsedCredentials != null) {
        throw new IllegalArgumentException(SR.MULTIPLE_CREDENTIALS_PROVIDED);
    }

    try {
        final boolean usePathStyleUris = Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri());
        this.fileServiceClient = new CloudFileClient(PathUtility.getServiceClientBaseAddress(
                this.getStorageUri(), usePathStyleUris), credentials != null ? credentials : parsedCredentials);
        this.name = PathUtility.getShareNameFromUri(this.storageUri.getPrimaryUri(), usePathStyleUris);
    }
    catch (final URISyntaxException e) {
        throw Utility.generateNewUnexpectedStorageException(e);
    }
}
 
Example #8
Source File: CloudFileDirectory.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the passed in URI. Then parses it and uses its components to populate this resource's properties.
 * 
 * @param completeUri
 *            A {@link StorageUri} object which represents the complete URI.
 * @param credentials
 *            A {@link StorageCredentials} object used to authenticate access.
 * @throws StorageException
 *             If a storage service error occurred.
 * @throws URISyntaxException 
 */
private void parseQueryAndVerify(final StorageUri completeUri, final StorageCredentials credentials)
        throws StorageException, URISyntaxException {
   Utility.assertNotNull("completeUri", completeUri);

    if (!completeUri.isAbsolute()) {
        throw new IllegalArgumentException(String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()));
    }

    this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri);
    
    final StorageCredentialsSharedAccessSignature parsedCredentials = 
            SharedAccessSignatureHelper.parseQuery(completeUri);

    if (credentials != null && parsedCredentials != null) {
        throw new IllegalArgumentException(SR.MULTIPLE_CREDENTIALS_PROVIDED);
    }

    try {
        final boolean usePathStyleUris = Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri());
        this.fileServiceClient = new CloudFileClient(PathUtility.getServiceClientBaseAddress(
                this.getStorageUri(), usePathStyleUris), credentials != null ? credentials : parsedCredentials);
        this.name = PathUtility.getDirectoryNameFromURI(this.storageUri.getPrimaryUri(), usePathStyleUris);
    }
    catch (final URISyntaxException e) {
        throw Utility.generateNewUnexpectedStorageException(e);
    }

    final HashMap<String, String[]> queryParameters = PathUtility.parseQueryString(completeUri.getQuery());

    final String[] snapshotIDs = queryParameters.get(Constants.QueryConstants.SHARE_SNAPSHOT);
    if (snapshotIDs != null && snapshotIDs.length > 0) {
        this.getShare().snapshotID = snapshotIDs[0];
    }
}
 
Example #9
Source File: CloudBlob.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the passed in URI. Then parses it and uses its components to populate this resource's properties.
 * 
 * @param completeUri
 *            A {@link StorageUri} object which represents the complete URI.
 * @param credentials
 *            A {@link StorageCredentials} object used to authenticate access.
 * @throws StorageException
 *             If a storage service error occurred.
 */
private void parseQueryAndVerify(final StorageUri completeUri, final StorageCredentials credentials)
        throws StorageException {
   Utility.assertNotNull("completeUri", completeUri);

    if (!completeUri.isAbsolute()) {
        throw new IllegalArgumentException(String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()));
    }

    this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri);
    
    final HashMap<String, String[]> queryParameters = PathUtility.parseQueryString(completeUri.getQuery());

    final String[] snapshotIDs = queryParameters.get(BlobConstants.SNAPSHOT);
    if (snapshotIDs != null && snapshotIDs.length > 0) {
        this.snapshotID = snapshotIDs[0];
    }
    
    final StorageCredentialsSharedAccessSignature parsedCredentials = 
            SharedAccessSignatureHelper.parseQuery(queryParameters);

    if (credentials != null && parsedCredentials != null) {
        throw new IllegalArgumentException(SR.MULTIPLE_CREDENTIALS_PROVIDED);
    }

    try {
        final boolean usePathStyleUris = Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri());
        this.blobServiceClient = new CloudBlobClient(PathUtility.getServiceClientBaseAddress(
                this.getStorageUri(), usePathStyleUris), credentials != null ? credentials : parsedCredentials);
        this.name = PathUtility.getBlobNameFromURI(this.storageUri.getPrimaryUri(), usePathStyleUris);
    }
    catch (final URISyntaxException e) {
        throw Utility.generateNewUnexpectedStorageException(e);
    }
}
 
Example #10
Source File: CloudBlobContainer.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the passed in URI. Then parses it and uses its components to populate this resource's properties.
 * 
 * @param completeUri
 *            A {@link StorageUri} object which represents the complete URI.
 * @param credentials
 *            A {@link StorageCredentials} object used to authenticate access.
 * @throws StorageException
 *             If a storage service error occurred.
 */
private void parseQueryAndVerify(final StorageUri completeUri, final StorageCredentials credentials)
        throws StorageException {
   Utility.assertNotNull("completeUri", completeUri);

    if (!completeUri.isAbsolute()) {
        throw new IllegalArgumentException(String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()));
    }

    this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri);
    
    final StorageCredentialsSharedAccessSignature parsedCredentials = 
            SharedAccessSignatureHelper.parseQuery(completeUri);

    if (credentials != null && parsedCredentials != null) {
        throw new IllegalArgumentException(SR.MULTIPLE_CREDENTIALS_PROVIDED);
    }

    try {
        final boolean usePathStyleUris = Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri());
        this.blobServiceClient = new CloudBlobClient(PathUtility.getServiceClientBaseAddress(
                this.getStorageUri(), usePathStyleUris), credentials != null ? credentials : parsedCredentials);
        this.name = PathUtility.getContainerNameFromUri(this.storageUri.getPrimaryUri(), usePathStyleUris);
    }
    catch (final URISyntaxException e) {
        throw Utility.generateNewUnexpectedStorageException(e);
    }
}
 
Example #11
Source File: CloudQueueTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Test
@Category({ DevFabricTests.class, DevStoreTests.class })
public void testSASClientParse() throws StorageException,  InvalidKeyException, URISyntaxException {
    // Add a policy, check setting and getting.
    SharedAccessQueuePolicy policy1 = new SharedAccessQueuePolicy();
    Calendar now = GregorianCalendar.getInstance();
    now.add(Calendar.MINUTE, -15);
    policy1.setSharedAccessStartTime(now.getTime());
    now.add(Calendar.MINUTE, 30);
    policy1.setSharedAccessExpiryTime(now.getTime());

    policy1.setPermissions(EnumSet.of(SharedAccessQueuePermissions.READ,
            SharedAccessQueuePermissions.PROCESSMESSAGES, SharedAccessQueuePermissions.ADD,
            SharedAccessQueuePermissions.UPDATE));

    String sasString = this.queue.generateSharedAccessSignature(policy1, null);

    URI queueUri = new URI("http://myaccount.queue.core.windows.net/myqueue");

    CloudQueueClient queueClient1 = new CloudQueueClient(new URI("http://myaccount.queue.core.windows.net/"),
            new StorageCredentialsSharedAccessSignature(sasString));

    CloudQueue queue1 = new CloudQueue(queueUri, queueClient1.getCredentials());
    queue1.getName();

    CloudQueueClient queueClient2 = new CloudQueueClient(new URI("http://myaccount.queue.core.windows.net/"),
            new StorageCredentialsSharedAccessSignature(sasString));
    CloudQueue queue2 = new CloudQueue(queueUri, queueClient2.getCredentials());
    queue2.getName();
}
 
Example #12
Source File: FileSasTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testFileSAS() throws InvalidKeyException, IllegalArgumentException, StorageException,
        URISyntaxException, InterruptedException {
    SharedAccessFilePolicy policy = createSharedAccessPolicy(
            EnumSet.of(SharedAccessFilePermissions.READ, SharedAccessFilePermissions.LIST), 300);
    FileSharePermissions perms = new FileSharePermissions();

    perms.getSharedAccessPolicies().put("readperm", policy);
    this.share.uploadPermissions(perms);
    Thread.sleep(30000);

    CloudFile sasFile = new CloudFile(
            new URI(this.file.getUri().toString() + "?" + this.file.generateSharedAccessSignature(null, "readperm")));
    sasFile.download(new ByteArrayOutputStream());

    // do not give the client and check that the new file's client has the correct permissions
    CloudFile fileFromUri = new CloudFile(PathUtility.addToQuery(this.file.getStorageUri(),
            this.file.generateSharedAccessSignature(null, "readperm")));
    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
            fileFromUri.getServiceClient().getCredentials().getClass().toString());
    
    // create credentials from sas
    StorageCredentials creds = new StorageCredentialsSharedAccessSignature(
            this.file.generateSharedAccessSignature(policy, null, null));
    CloudFileClient client = new CloudFileClient(sasFile.getServiceClient().getStorageUri(), creds);

    CloudFile fileFromClient = client.getShareReference(this.file.getShare().getName()).getRootDirectoryReference()
            .getFileReference(this.file.getName());
    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
            fileFromClient.getServiceClient().getCredentials().getClass().toString());
    assertEquals(client, fileFromClient.getServiceClient());
}
 
Example #13
Source File: AzureStorageClient.java    From azure-kusto-java with MIT License 5 votes vote down vote up
String getBlobPathWithSas(CloudBlockBlob blob) {
    Ensure.argIsNotNull(blob, "blob");

    StorageCredentialsSharedAccessSignature signature =
            (StorageCredentialsSharedAccessSignature) blob.getServiceClient().getCredentials();
    return blob.getStorageUri().getPrimaryUri().toString() + "?" + signature.getToken();
}
 
Example #14
Source File: CloudBlockBlobTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Start copying a file and then abort
 *
 * @throws StorageException
 * @throws URISyntaxException
 * @throws IOException
 * @throws InvalidKeyException
 * @throws InterruptedException
 */
@Test
@Category({ DevFabricTests.class, DevStoreTests.class })
public void testCopyFileAbort()
        throws StorageException, URISyntaxException, IOException, InvalidKeyException, InterruptedException {
    final int length = 128;
    final CloudFileShare share = FileTestHelper.getRandomShareReference();
    share.create();
    final CloudFile source = FileTestHelper.uploadNewFile(share, length, null);

    // Source SAS must have read permissions
    SharedAccessFilePolicy policy = new SharedAccessFilePolicy();
    policy.setPermissions(EnumSet.of(SharedAccessFilePermissions.READ));

    Calendar cal = Calendar.getInstance(Utility.UTC_ZONE);
    cal.add(Calendar.MINUTE, 5);
    policy.setSharedAccessExpiryTime(cal.getTime());
    String sasToken = source.generateSharedAccessSignature(policy, null, null);

    // Start copy and wait for completion
    final CloudBlockBlob destination = this.container.getBlockBlobReference(source.getName() + "copyed");
    StorageCredentialsSharedAccessSignature credentials = new StorageCredentialsSharedAccessSignature(sasToken);
    destination.startCopy(new CloudFile(credentials.transformUri(source.getUri())));

    try {
        destination.abortCopy(destination.getProperties().getCopyState().getCopyId());
        BlobTestHelper.waitForCopy(destination);
        fail();
    }
    catch (StorageException e) {
        if (!e.getErrorCode().contains("NoPendingCopyOperation")) {
            throw e;
        }
    }
    finally {
        share.deleteIfExists();
    }
}
 
Example #15
Source File: AzureNativeFileSystemStore.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to Azure storage using shared access signature credentials.
 */
private void connectUsingSASCredentials(final String accountName,
    final String containerName, final String sas) throws InvalidKeyException,
    StorageException, IOException, URISyntaxException {
  StorageCredentials credentials = new StorageCredentialsSharedAccessSignature(
      sas);
  connectingUsingSAS = true;
  connectUsingCredentials(accountName, credentials, containerName);
}
 
Example #16
Source File: AzureStorageQueueListReaderTest.java    From components with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    dummyCredential = new StorageCredentialsSharedAccessSignature("fakesaas");
    properties = new TAzureStorageQueueListProperties(PROP_ + "QueueList");
    properties.setupProperties();
    properties.connection = getValidFakeConnection();
}
 
Example #17
Source File: SasTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Test
@Category(SlowTests.class)
public void testBlobSaS() throws InvalidKeyException, IllegalArgumentException, StorageException,
        URISyntaxException, InterruptedException {
    SharedAccessBlobPolicy sp = createSharedAccessPolicy(
            EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.LIST), 3600);
    BlobContainerPermissions perms = new BlobContainerPermissions();

    perms.getSharedAccessPolicies().put("readperm", sp);
    this.container.uploadPermissions(perms);
    Thread.sleep(30000);

    CloudBlockBlob sasBlob = new CloudBlockBlob(new URI(this.blob.getUri().toString() + "?"
            + this.blob.generateSharedAccessSignature(null, "readperm")));
    sasBlob.download(new ByteArrayOutputStream());

    // do not give the client and check that the new blob's client has the correct perms
    CloudBlob blobFromUri = new CloudBlockBlob(PathUtility.addToQuery(this.blob.getStorageUri(),
            this.blob.generateSharedAccessSignature(null, "readperm")));
    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(), blobFromUri.getServiceClient()
            .getCredentials().getClass().toString());

    // create credentials from sas
    StorageCredentials creds = new StorageCredentialsSharedAccessSignature(
            this.blob.generateSharedAccessSignature(null, "readperm"));
    CloudBlobClient bClient = new CloudBlobClient(sasBlob.getServiceClient().getStorageUri(), creds);

    CloudBlockBlob blobFromClient = bClient.getContainerReference(this.blob.getContainer().getName())
            .getBlockBlobReference(this.blob.getName());
    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(), blobFromClient.getServiceClient()
            .getCredentials().getClass().toString());
    assertEquals(bClient, blobFromClient.getServiceClient());
}
 
Example #18
Source File: SasTests.java    From azure-storage-android with Apache License 2.0 4 votes vote down vote up
@Test
@Category ({ SecondaryTests.class, SlowTests.class })
public void testContainerSaS() throws IllegalArgumentException, StorageException, URISyntaxException,
        InvalidKeyException, InterruptedException {
    SharedAccessBlobPolicy sp1 = createSharedAccessPolicy(
            EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.WRITE,
                    SharedAccessBlobPermissions.LIST, SharedAccessBlobPermissions.DELETE), 3600);
    SharedAccessBlobPolicy sp2 = createSharedAccessPolicy(
            EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.LIST), 3600);
    BlobContainerPermissions perms = new BlobContainerPermissions();

    perms.getSharedAccessPolicies().put("full", sp1);
    perms.getSharedAccessPolicies().put("readlist", sp2);
    this.container.uploadPermissions(perms);
    Thread.sleep(30000);

    String containerReadListSas = this.container.generateSharedAccessSignature(sp2, null);
    CloudBlobContainer readListContainer = new CloudBlobContainer(PathUtility.addToQuery(this.container.getUri(),
            containerReadListSas));

    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(), readListContainer.getServiceClient()
            .getCredentials().getClass().toString());

    CloudBlockBlob blobFromSasContainer = readListContainer.getBlockBlobReference(this.blob.getName());
    blobFromSasContainer.download(new ByteArrayOutputStream());

    // do not give the client and check that the new container's client has the correct perms
    CloudBlobContainer containerFromUri = new CloudBlobContainer(PathUtility.addToQuery(
            readListContainer.getStorageUri(), this.container.generateSharedAccessSignature(null, "readlist")));
    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(), containerFromUri.getServiceClient()
            .getCredentials().getClass().toString());
    
    // create credentials from sas
    StorageCredentials creds = new StorageCredentialsSharedAccessSignature(
            this.container.generateSharedAccessSignature(null, "readlist"));
    CloudBlobClient bClient = new CloudBlobClient(this.container.getServiceClient().getStorageUri(), creds);

    CloudBlobContainer containerFromClient = bClient.getContainerReference(this.container.getName());
    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(), containerFromClient.getServiceClient()
            .getCredentials().getClass().toString());
    assertEquals(bClient, containerFromClient.getServiceClient());
}
 
Example #19
Source File: TestAzureStorageUtilsGetStorageCredentialsDetails.java    From nifi with Apache License 2.0 4 votes vote down vote up
private void assertStorageCredentialsDetailsAccountNameAndSasToken(AzureStorageCredentialsDetails storageCredentialsDetails) {
    assertEquals(ACCOUNT_NAME_VALUE, storageCredentialsDetails.getStorageAccountName());
    assertTrue(storageCredentialsDetails.getStorageCredentials() instanceof StorageCredentialsSharedAccessSignature);
    StorageCredentialsSharedAccessSignature storageCredentials = (StorageCredentialsSharedAccessSignature) storageCredentialsDetails.getStorageCredentials();
    assertEquals(SAS_TOKEN_VALUE, storageCredentials.getToken());
}
 
Example #20
Source File: AzureConnectionWithSasService.java    From components with Apache License 2.0 4 votes vote down vote up
@Override
public CloudStorageAccount getCloudStorageAccount() throws InvalidKeyException, URISyntaxException {
    StorageCredentials credentials = new StorageCredentialsSharedAccessSignature(sasToken);
    return new CloudStorageAccount(credentials, true, endpointSuffix, accountName);
}
 
Example #21
Source File: SasTests.java    From azure-storage-android with Apache License 2.0 4 votes vote down vote up
@Test
@Category(SecondaryTests.class)
public void testIpAcl()
        throws StorageException, URISyntaxException, InvalidKeyException, InterruptedException, UnknownHostException {
    
    // Generate policies
    SharedAccessBlobPolicy sp = createSharedAccessPolicy(
            EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.LIST), 3600);
    IPRange range1 = new IPRange("0.0.0.0", "255.255.255.255");
    IPRange range2 = new IPRange("0.0.0.0");
    
    // Ensure access attempt from invalid IP fails
    IPRange sourceIP = null;
    try {
        String containerSasNone = this.container.generateSharedAccessSignature(sp, null, range2, null);
        CloudBlobContainer noneContainer =
                new CloudBlobContainer(PathUtility.addToQuery(this.container.getUri(), containerSasNone));

        assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
                noneContainer.getServiceClient().getCredentials().getClass().toString());

        CloudBlockBlob noneBlob = noneContainer.getBlockBlobReference(this.blob.getName());
        noneBlob.download(new ByteArrayOutputStream());
        fail();
    }
    catch (StorageException ex) {
        assertEquals(HttpURLConnection.HTTP_FORBIDDEN, ex.getHttpStatusCode());
        
        final String[] words = ex.getMessage().split(" ");
        // final word
        String lastWord = words[words.length - 1];
        // strip trailing period
        lastWord = lastWord.substring(0, lastWord.length() - 1);
        
        sourceIP = new IPRange(lastWord);
    }
    
    // Ensure access attempt from the single allowed IP succeeds
    String containerSasOne = this.container.generateSharedAccessSignature(sp, null, sourceIP, null);
    CloudBlobContainer oneContainer =
            new CloudBlobContainer(PathUtility.addToQuery(this.container.getUri(), containerSasOne));

    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
            oneContainer.getServiceClient().getCredentials().getClass().toString());

    CloudBlockBlob oneBlob = oneContainer.getBlockBlobReference(this.blob.getName());
    oneBlob.download(new ByteArrayOutputStream());

    // Ensure access attempt from one of many valid IPs succeeds
    String containerSasAll = this.container.generateSharedAccessSignature(sp, null, range1, null);
    CloudBlobContainer allContainer =
            new CloudBlobContainer(PathUtility.addToQuery(this.container.getUri(), containerSasAll));

    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
            allContainer.getServiceClient().getCredentials().getClass().toString());

    CloudBlockBlob allBlob = allContainer.getBlockBlobReference(this.blob.getName());
    allBlob.download(new ByteArrayOutputStream());
}
 
Example #22
Source File: CloudFileTests.java    From azure-storage-android with Apache License 2.0 4 votes vote down vote up
private CloudFile doCloudBlobCopy(CloudBlob source, int length) throws Exception {
    Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    cal.setTime(new Date());
    cal.add(Calendar.MINUTE, 5);
    
    // Source SAS must have read permissions
    SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
    policy.setPermissions(EnumSet.of(SharedAccessBlobPermissions.READ));
    policy.setSharedAccessExpiryTime(cal.getTime());

    String sasToken = source.generateSharedAccessSignature(policy, null, null);

    // Get destination reference
    final CloudFile destination = this.share.getRootDirectoryReference().getFileReference("destination");
    
    // Start copy and wait for completion
    StorageCredentialsSharedAccessSignature credentials = new StorageCredentialsSharedAccessSignature(sasToken);
    Constructor<? extends CloudBlob> blobType = source.getClass().getConstructor(URI.class);
    String copyId = destination.startCopy(blobType.newInstance(credentials.transformUri(source.getUri())));
    FileTestHelper.waitForCopy(destination);
    destination.downloadAttributes();
    
    // Check original file references for equality
    assertEquals(CopyStatus.SUCCESS, destination.getCopyState().getStatus());
    assertEquals(source.getServiceClient().getCredentials().transformUri(source.getUri()).getPath(),
            destination.getCopyState().getSource().getPath());
    assertEquals(length, destination.getCopyState().getTotalBytes().intValue());
    assertEquals(length, destination.getCopyState().getBytesCopied().intValue());
    assertEquals(copyId, destination.getProperties().getCopyState().getCopyId());

    // Attempt to abort the completed copy operation.
    try {
        destination.abortCopy(destination.getCopyState().getCopyId());
        FileTestHelper.waitForCopy(destination);
        fail();
    }
    catch (StorageException ex) {
        assertEquals(HttpURLConnection.HTTP_CONFLICT, ex.getHttpStatusCode());
    }

    assertNotNull(destination.getProperties().getEtag());
    assertFalse(source.getProperties().getEtag().equals(destination.getProperties().getEtag()));

    source.downloadAttributes();
    FileProperties prop1 = destination.getProperties();
    BlobProperties prop2 = source.getProperties();

    assertEquals(prop1.getCacheControl(), prop2.getCacheControl());
    assertEquals(prop1.getContentEncoding(), prop2.getContentEncoding());
    assertEquals(prop1.getContentLanguage(), prop2.getContentLanguage());
    assertEquals(prop1.getContentMD5(), prop2.getContentMD5());
    assertEquals(prop1.getContentType(), prop2.getContentType());

    assertEquals("value", destination.getMetadata().get("Test"));
    return destination;
}
 
Example #23
Source File: CloudBlockBlobTests.java    From azure-storage-android with Apache License 2.0 4 votes vote down vote up
@Test
@Category(SlowTests.class)
public void testCopyFileSas()
        throws InvalidKeyException, URISyntaxException, StorageException, IOException, InterruptedException {
    // Create source on server.
    final CloudFileShare share = FileTestHelper.getRandomShareReference();
    try {
        share.create();
        final CloudFile source = share.getRootDirectoryReference().getFileReference("source");

        final String data = "String data";
        source.getMetadata().put("Test", "value");
        source.uploadText(data, Constants.UTF8_CHARSET, null, null, null);

        Calendar cal = Calendar.getInstance(Utility.UTC_ZONE);
        cal.add(Calendar.MINUTE, 5);

        // Source SAS must have read permissions
        SharedAccessFilePolicy policy = new SharedAccessFilePolicy();
        policy.setPermissions(EnumSet.of(SharedAccessFilePermissions.READ));
        policy.setSharedAccessExpiryTime(cal.getTime());

        String sasToken = source.generateSharedAccessSignature(policy, null, null);

        // Get destination reference
        final CloudBlockBlob destination = this.container.getBlockBlobReference("destination");

        // Start copy and wait for completion
        StorageCredentialsSharedAccessSignature credentials = new StorageCredentialsSharedAccessSignature(sasToken);
        String copyId = destination.startCopy(new CloudFile(credentials.transformUri(source.getUri())));
        BlobTestHelper.waitForCopy(destination);
        destination.downloadAttributes();
        assertNotNull(destination.getProperties().getEtag());

        // Check original file references for equality
        assertEquals(CopyStatus.SUCCESS, destination.getCopyState().getStatus());
        assertEquals(source.getServiceClient().getCredentials().transformUri(source.getUri()).getPath(),
                destination.getCopyState().getSource().getPath());
        assertEquals(data.length(), destination.getCopyState().getTotalBytes().intValue());
        assertEquals(data.length(), destination.getCopyState().getBytesCopied().intValue());
        assertEquals(copyId, destination.getProperties().getCopyState().getCopyId());

        // Attempt to abort the completed copy operation.
        try {
            destination.abortCopy(destination.getCopyState().getCopyId());
            fail();
        }
        catch (StorageException ex) {
            assertEquals(HttpURLConnection.HTTP_CONFLICT, ex.getHttpStatusCode());
        }

        String copyData = destination.downloadText(Constants.UTF8_CHARSET, null, null, null);
        assertEquals(data, copyData);

        source.downloadAttributes();
        BlobProperties prop1 = destination.getProperties();
        FileProperties prop2 = source.getProperties();

        assertEquals(prop1.getCacheControl(), prop2.getCacheControl());
        assertEquals(prop1.getContentEncoding(), prop2.getContentEncoding());
        assertEquals(prop1.getContentLanguage(), prop2.getContentLanguage());
        assertEquals(prop1.getContentMD5(), prop2.getContentMD5());
        assertEquals(prop1.getContentType(), prop2.getContentType());

        assertEquals("value", destination.getMetadata().get("Test"));
        assertEquals(1, destination.getMetadata().size());
    }
    finally {
        share.deleteIfExists();
    }
}
 
Example #24
Source File: CloudQueueTests.java    From azure-storage-android with Apache License 2.0 4 votes vote down vote up
@Test
@Category({ DevFabricTests.class, DevStoreTests.class, SlowTests.class })
public void testQueueSAS() throws StorageException, URISyntaxException, InvalidKeyException, InterruptedException {
    this.queue.addMessage(new CloudQueueMessage("sas queue test"));
    QueuePermissions expectedPermissions;

    expectedPermissions = new QueuePermissions();
    // Add a policy, check setting and getting.
    SharedAccessQueuePolicy policy1 = new SharedAccessQueuePolicy();
    Calendar now = GregorianCalendar.getInstance();
    now.add(Calendar.MINUTE, -15);
    policy1.setSharedAccessStartTime(now.getTime());
    now.add(Calendar.MINUTE, 30);
    policy1.setSharedAccessExpiryTime(now.getTime());
    String identifier = UUID.randomUUID().toString();

    policy1.setPermissions(EnumSet.of(SharedAccessQueuePermissions.READ,
            SharedAccessQueuePermissions.PROCESSMESSAGES, SharedAccessQueuePermissions.ADD,
            SharedAccessQueuePermissions.UPDATE));
    expectedPermissions.getSharedAccessPolicies().put(identifier, policy1);

    this.queue.uploadPermissions(expectedPermissions);
    Thread.sleep(30000);

    CloudQueue identifierSasQueue = new CloudQueue(PathUtility.addToQuery(this.queue.getUri(),
            this.queue.generateSharedAccessSignature(null, identifier)));

    identifierSasQueue.downloadAttributes();
    identifierSasQueue.exists();

    identifierSasQueue.addMessage(new CloudQueueMessage("message"), 20, 0, null, null);
    CloudQueueMessage message1 = identifierSasQueue.retrieveMessage();
    identifierSasQueue.deleteMessage(message1);

    CloudQueue policySasQueue = new CloudQueue(PathUtility.addToQuery(this.queue.getUri(),
            this.queue.generateSharedAccessSignature(policy1, null)));
    policySasQueue.exists();
    policySasQueue.downloadAttributes();

    policySasQueue.addMessage(new CloudQueueMessage("message"), 20, 0, null, null);
    CloudQueueMessage message2 = policySasQueue.retrieveMessage();
    policySasQueue.deleteMessage(message2);

    // do not give the client and check that the new queue's client has the correct perms
    CloudQueue queueFromUri = new CloudQueue(PathUtility.addToQuery(this.queue.getStorageUri(),
            this.queue.generateSharedAccessSignature(null, "readperm")));
    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(), queueFromUri.getServiceClient()
            .getCredentials().getClass().toString());

    // pass in a client which will have different permissions and check the sas permissions are used
    // and that the properties set in the old service client are passed to the new client
    CloudQueueClient queueClient = policySasQueue.getServiceClient();

    // set some arbitrary settings to make sure they are passed on
    queueClient.getDefaultRequestOptions().setLocationMode(LocationMode.PRIMARY_THEN_SECONDARY);
    queueClient.getDefaultRequestOptions().setTimeoutIntervalInMs(1000);
    queueClient.getDefaultRequestOptions().setRetryPolicyFactory(new RetryNoRetry());

    queueFromUri = new CloudQueue(PathUtility.addToQuery(this.queue.getStorageUri(),
            this.queue.generateSharedAccessSignature(null, "readperm")));
    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(), queueFromUri.getServiceClient()
            .getCredentials().getClass().toString());
}
 
Example #25
Source File: TableTests.java    From azure-storage-android with Apache License 2.0 4 votes vote down vote up
@Test
@Category(SlowTests.class)
public void testTableSas() throws StorageException, URISyntaxException, InvalidKeyException, InterruptedException {
    CloudTableClient tClient = TableTestHelper.createCloudTableClient();

    // use capital letters to make sure SAS signature converts name to lower case correctly
    String name = "CAPS" + TableTestHelper.generateRandomTableName();
    CloudTable table = tClient.getTableReference(name);
    table.create();

    TablePermissions expectedPermissions = new TablePermissions();
    String identifier = UUID.randomUUID().toString();
    // Add a policy, check setting and getting.
    SharedAccessTablePolicy policy1 = new SharedAccessTablePolicy();
    Calendar now = GregorianCalendar.getInstance();
    now.add(Calendar.MINUTE, -10);
    policy1.setSharedAccessStartTime(now.getTime());
    now.add(Calendar.MINUTE, 30);
    policy1.setSharedAccessExpiryTime(now.getTime());

    policy1.setPermissions(EnumSet.of(SharedAccessTablePermissions.ADD, SharedAccessTablePermissions.QUERY,
            SharedAccessTablePermissions.UPDATE, SharedAccessTablePermissions.DELETE));
    expectedPermissions.getSharedAccessPolicies().put(identifier, policy1);

    table.uploadPermissions(expectedPermissions);
    Thread.sleep(30000);

    // Insert 500 entities in Batches to query
    for (int i = 0; i < 5; i++) {
        TableBatchOperation batch = new TableBatchOperation();

        for (int j = 0; j < 100; j++) {
            Class1 ent = TableTestHelper.generateRandomEntity("javatables_batch_" + Integer.toString(i));
            ent.setRowKey(String.format("%06d", j));
            batch.insert(ent);
        }

        table.execute(batch);
    }

    String sasString = table.generateSharedAccessSignature(policy1, null, "javatables_batch_0", "0",
            "javatables_batch_9", "9");
    CloudTableClient tableClientFromPermission = new CloudTableClient(tClient.getEndpoint(),
            new StorageCredentialsSharedAccessSignature(sasString));

    CloudTable policySasTable = tableClientFromPermission.getTableReference(name);

    // do not give the client and check that the new table's client has the correct perms
    CloudTable tableFromUri = new CloudTable(PathUtility.addToQuery(table.getStorageUri(), table
            .generateSharedAccessSignature((SharedAccessTablePolicy) null, identifier, "javatables_batch_0", "0",
                    "javatables_batch_9", "9")));
    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(), tableFromUri.getServiceClient()
            .getCredentials().getClass().toString());

    // create credentials from sas
    StorageCredentials creds = new StorageCredentialsSharedAccessSignature(
            table.generateSharedAccessSignature((SharedAccessTablePolicy) null, identifier, "javatables_batch_0", "0",
                    "javatables_batch_9", "9"));
    CloudTableClient tableClient = new CloudTableClient(policySasTable.getServiceClient().getStorageUri(), creds);

    // set some arbitrary settings to make sure they are passed on
    tableClient.getDefaultRequestOptions().setLocationMode(LocationMode.PRIMARY_THEN_SECONDARY);
    tableClient.getDefaultRequestOptions().setTimeoutIntervalInMs(1000);
    tableClient.getDefaultRequestOptions().setTablePayloadFormat(TablePayloadFormat.JsonNoMetadata);
    tableClient.getDefaultRequestOptions().setRetryPolicyFactory(new RetryNoRetry());

    tableFromUri = tableClient.getTableReference(table.getName());
    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(), tableFromUri.getServiceClient()
            .getCredentials().getClass().toString());

    assertEquals(tableClient.getDefaultRequestOptions().getLocationMode(), tableFromUri.getServiceClient()
            .getDefaultRequestOptions().getLocationMode());
    assertEquals(tableClient.getDefaultRequestOptions().getTimeoutIntervalInMs(), tableFromUri.getServiceClient()
            .getDefaultRequestOptions().getTimeoutIntervalInMs());
    assertEquals(tableClient.getDefaultRequestOptions().getTablePayloadFormat(), tableFromUri.getServiceClient()
            .getDefaultRequestOptions().getTablePayloadFormat());
    assertEquals(tableClient.getDefaultRequestOptions().getRetryPolicyFactory().getClass(), tableFromUri
            .getServiceClient().getDefaultRequestOptions().getRetryPolicyFactory().getClass());
}
 
Example #26
Source File: CloudBlockBlobTests.java    From azure-storage-android with Apache License 2.0 4 votes vote down vote up
@Test
@Category({ DevFabricTests.class, DevStoreTests.class, SlowTests.class })
public void testCopyFileWithMetadataOverride()
        throws URISyntaxException, StorageException, IOException, InterruptedException, InvalidKeyException {
    Calendar calendar = Calendar.getInstance(Utility.UTC_ZONE);
    String data = "String data";

    final CloudFileShare share = FileTestHelper.getRandomShareReference();
    try {
        share.create();
        final CloudFile source = share.getRootDirectoryReference().getFileReference("source");
        FileTestHelper.setFileProperties(source);

        // do this to make sure the set MD5 can be compared, otherwise when the dummy value
        // doesn't match the actual MD5 an exception would be thrown
        BlobRequestOptions options = new BlobRequestOptions();
        options.setDisableContentMD5Validation(true);

        source.getMetadata().put("Test", "value");
        source.uploadText(data);

        calendar.add(Calendar.MINUTE, 5);

        // Source SAS must have read permissions
        SharedAccessFilePolicy policy = new SharedAccessFilePolicy();
        policy.setPermissions(EnumSet.of(SharedAccessFilePermissions.READ));
        policy.setSharedAccessExpiryTime(calendar.getTime());

        String sasToken = source.generateSharedAccessSignature(policy, null, null);

        // Get source BlockBlob reference
        StorageCredentialsSharedAccessSignature credentials = new StorageCredentialsSharedAccessSignature(sasToken);
        CloudBlockBlob destination = this.container.getBlockBlobReference("copy");

        destination.getMetadata().put("Test2", "value2");
        String copyId = destination.startCopy(
                FileTestHelper.defiddler(new CloudFile(credentials.transformUri(source.getUri()))));
        BlobTestHelper.waitForCopy(destination);
        destination.downloadAttributes();

        assertEquals(CopyStatus.SUCCESS, destination.getCopyState().getStatus());
        assertEquals(source.getServiceClient().getCredentials().transformUri(source.getUri()).getPath(),
                destination.getCopyState().getSource().getPath());
        assertEquals(data.length(), destination.getCopyState().getTotalBytes().intValue());
        assertEquals(data.length(), destination.getCopyState().getBytesCopied().intValue());
        assertEquals(copyId, destination.getCopyState().getCopyId());
        assertTrue(0 < destination.getCopyState().getCompletionTime().compareTo(
                new Date(calendar.get(Calendar.MINUTE) - 6)));

        String copyData = destination.downloadText(Constants.UTF8_CHARSET, null, options, null);
        assertEquals(data, copyData);

        source.downloadAttributes();
        BlobProperties prop1 = destination.getProperties();
        FileProperties prop2 = source.getProperties();

        assertEquals(prop1.getCacheControl(), prop2.getCacheControl());
        assertEquals(prop1.getContentEncoding(), prop2.getContentEncoding());
        assertEquals(prop1.getContentDisposition(),
                prop2.getContentDisposition());
        assertEquals(prop1.getContentLanguage(), prop2.getContentLanguage());
        assertEquals(prop1.getContentMD5(), prop2.getContentMD5());
        assertEquals(prop1.getContentType(), prop2.getContentType());

        assertEquals("value2", destination.getMetadata().get("Test2"));
        assertFalse(destination.getMetadata().containsKey("Test"));
        assertEquals(1, destination.getMetadata().size());
    }
    finally {
        share.deleteIfExists();
    }
}
 
Example #27
Source File: FileSasTests.java    From azure-storage-android with Apache License 2.0 4 votes vote down vote up
@Test
@Category({ SecondaryTests.class, SlowTests.class })
public void testShareSAS() throws IllegalArgumentException, StorageException, URISyntaxException,
        InvalidKeyException, InterruptedException {
    SharedAccessFilePolicy policy1 = createSharedAccessPolicy(
            EnumSet.of(SharedAccessFilePermissions.READ, SharedAccessFilePermissions.WRITE,
            SharedAccessFilePermissions.LIST, SharedAccessFilePermissions.DELETE), 300);
    SharedAccessFilePolicy policy2 = createSharedAccessPolicy(
            EnumSet.of(SharedAccessFilePermissions.READ, SharedAccessFilePermissions.LIST), 300);
    FileSharePermissions permissions = new FileSharePermissions();

    permissions.getSharedAccessPolicies().put("full", policy1);
    permissions.getSharedAccessPolicies().put("readlist", policy2);
    this.share.uploadPermissions(permissions);
    Thread.sleep(30000);

    String shareReadListSas = this.share.generateSharedAccessSignature(policy2, null);
    CloudFileShare readListShare =
            new CloudFileShare(PathUtility.addToQuery(this.share.getUri(), shareReadListSas));

    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
            readListShare.getServiceClient().getCredentials().getClass().toString());

    CloudFile fileFromSasShare = readListShare.getRootDirectoryReference().getFileReference(this.file.getName());
    fileFromSasShare.download(new ByteArrayOutputStream());

    // do not give the client and check that the new share's client has the correct perms
    CloudFileShare shareFromUri = new CloudFileShare(PathUtility.addToQuery(
            readListShare.getStorageUri(), this.share.generateSharedAccessSignature(null, "readlist")));
    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
            shareFromUri.getServiceClient().getCredentials().getClass().toString());

    // create credentials from sas
    StorageCredentials creds = new StorageCredentialsSharedAccessSignature(
            this.share.generateSharedAccessSignature(null, "readlist"));
    CloudFileClient client = new CloudFileClient(this.share.getServiceClient().getStorageUri(), creds);

    CloudFileShare shareFromClient = client.getShareReference(readListShare.getName());
    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
            shareFromClient.getServiceClient().getCredentials().getClass().toString());
    assertEquals(client, shareFromClient.getServiceClient());
}
 
Example #28
Source File: FileSasTests.java    From azure-storage-android with Apache License 2.0 4 votes vote down vote up
@Test
@Category({ SecondaryTests.class })
public void testIpAcl()
        throws StorageException, URISyntaxException, InvalidKeyException, InterruptedException, UnknownHostException {
    
    // Generate policies
    SharedAccessFilePolicy policy = createSharedAccessPolicy(
            EnumSet.of(SharedAccessFilePermissions.READ, SharedAccessFilePermissions.LIST), 300);
    IPRange range1 = new IPRange("0.0.0.0", "255.255.255.255");
    IPRange range2 = new IPRange("0.0.0.0");
    
    // Ensure access attempt from invalid IP fails
    IPRange sourceIP = null;
    try {
        String shareSasNone = this.share.generateSharedAccessSignature(policy, null, range2, null);
        CloudFileShare noneShare =
                new CloudFileShare(PathUtility.addToQuery(this.share.getUri(), shareSasNone));

        assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
                noneShare.getServiceClient().getCredentials().getClass().toString());

        CloudFile noneFile = noneShare.getRootDirectoryReference().getFileReference(this.file.getName());
        noneFile.download(new ByteArrayOutputStream());
        fail();
    }
    catch (StorageException ex) {
        assertEquals(HttpURLConnection.HTTP_FORBIDDEN, ex.getHttpStatusCode());
        
        final String[] words = ex.getMessage().split(" ");
        // final word
        String lastWord = words[words.length - 1];
        // strip trailing period
        lastWord = lastWord.substring(0, lastWord.length() - 1);
        
        sourceIP = new IPRange(lastWord);
    }
    
    // Ensure access attempt from the single allowed IP succeeds
    String shareSasOne = this.share.generateSharedAccessSignature(policy, null, sourceIP, null);
    CloudFileShare oneShare =
            new CloudFileShare(PathUtility.addToQuery(this.share.getUri(), shareSasOne));

    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
            oneShare.getServiceClient().getCredentials().getClass().toString());

    CloudFile oneFile = oneShare.getRootDirectoryReference().getFileReference(this.file.getName());
    oneFile.download(new ByteArrayOutputStream());

    // Ensure access attempt from one of many valid IPs succeeds
    String shareSasAll = this.share.generateSharedAccessSignature(policy, null, range1, null);
    CloudFileShare allShare =
            new CloudFileShare(PathUtility.addToQuery(this.share.getUri(), shareSasAll));

    assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
            allShare.getServiceClient().getCredentials().getClass().toString());

    CloudFile allFile = allShare.getRootDirectoryReference().getFileReference(this.file.getName());
    allFile.download(new ByteArrayOutputStream());
}
 
Example #29
Source File: SharedAccessSignatureHelper.java    From azure-storage-android with Apache License 2.0 2 votes vote down vote up
/**
 * Parses the query parameters and populates a StorageCredentialsSharedAccessSignature object if one is present.
 * 
 * @param completeUri
 *            A {@link StorageUri} object which represents the complete Uri.
 *            
 * @return The StorageCredentialsSharedAccessSignature if one is present, otherwise null.
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 */
public static StorageCredentialsSharedAccessSignature parseQuery(final StorageUri completeUri) throws StorageException {
    final HashMap<String, String[]> queryParameters = PathUtility.parseQueryString(completeUri.getQuery());
    return parseQuery(queryParameters);
}
 
Example #30
Source File: StorageCredentialsHelper.java    From azure-storage-android with Apache License 2.0 2 votes vote down vote up
/**
 *  RESERVED, for internal use only. Gets a value indicating whether a
 *  client can be generated under the Shared Key or Shared Access Signature
 *  authentication schemes using the specified credentials.
 *  @return <Code>true</Code> if a client can be generated with these
 *  credentials; otherwise, <Code>false</Code>
 */
public static boolean canCredentialsGenerateClient(final StorageCredentials creds) {
    return canCredentialsSignRequest(creds) || creds.getClass().equals(StorageCredentialsSharedAccessSignature.class);
}