Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

POC: Storage Browser #5

Open
wants to merge 3 commits into
base: storage-browser/main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 37 additions & 12 deletions packages/core/src/parseAmplifyOutputs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,18 +342,43 @@ function createBucketInfoMap(
): Record<string, BucketInfo> {
const mappedBuckets: Record<string, BucketInfo> = {};

buckets.forEach(({ name, bucket_name: bucketName, aws_region: region }) => {
if (name in mappedBuckets) {
throw new Error(
`Duplicate friendly name found: ${name}. Name must be unique.`,
);
}

mappedBuckets[name] = {
bucketName,
region,
};
});
buckets.forEach(
({ name, bucket_name: bucketName, aws_region: region, paths }) => {
if (name in mappedBuckets) {
throw new Error(
`Duplicate friendly name found: ${name}. Name must be unique.`,
);
}

mappedBuckets[name] = {
bucketName,
region,
paths,
};
},
);

return mappedBuckets;
}

// eslint-disable-next-line unused-imports/no-unused-vars
const parseAccessRules = (
paths: AmplifyOutputsStorageBucketProperties['paths'],
): Record<string, any> => {
const output: Record<string, any> = {};

for (const [path, roles] of Object.entries(paths)) {
for (const [role, permissions] of Object.entries(roles)) {
if (!output[role]) {
output[role] = [];
}
if (role === 'authenticated' || role === 'guest') {
output[role].push({ [path]: permissions });
} else if (role.startsWith('groups') || role.startsWith('entity')) {
output[role].push({ [path]: permissions });
}
}
}

return output;
};
1 change: 1 addition & 0 deletions packages/core/src/singleton/AmplifyOutputs/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export interface AmplifyOutputsStorageBucketProperties {
bucket_name: string;
/** Region for the bucket */
aws_region: string;
paths: Record<string, Record<string, string[]>>;
}
export interface AmplifyOutputsStorageProperties {
/** Default region for Storage */
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/singleton/Storage/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ export interface BucketInfo {
bucketName: string;
/** Region of the bucket */
region: string;
/** Path to object provisioned */
paths: Record<string, Record<string, string[]>>;
}
export interface S3ProviderConfig {
S3: {
Expand Down
1 change: 1 addition & 0 deletions packages/storage/src/providers/s3/types/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export type LocationCredentialsProvider = (
export interface BucketInfo {
bucketName: string;
region: string;
paths: Record<string, Record<string, string[]>>;
}

export type StorageBucket = string | BucketInfo;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { Amplify, fetchAuthSession } from '@aws-amplify/core';

import { GetLocationCredentials, ListPaths } from '../types';
import { BucketInfo } from '../../providers/s3/types/options';

interface Location {
type: 'PREFIX';
permission: string[];
scope: {
bucketName: string;
path: string;
};
}

export interface AuthConfigAdapter {
/** outputs Scope(path), permission (read/write/readwrite), type(prefix/bucket/object) */
listLocations: ListPaths;
/** basically fetch auth session */
getLocationCredentials?: GetLocationCredentials;
}

export const createAmplifyAuthConfigAdapter = (): AuthConfigAdapter => {
const listLocations = createAmplifyListLocationsHandler();

return { listLocations };
};

const createAmplifyListLocationsHandler = (): ListPaths => {
return async function listLocations(input = {}) {
const { buckets } = Amplify.getConfig().Storage!.S3!;

if (!buckets) {
return { locations: [] };
}
// eslint-disable-next-line no-debugger
debugger;

const { tokens, identityId } = await fetchAuthSession();
const userGroups = tokens?.accessToken.payload['cognito:groups'];

// eslint-disable-next-line unused-imports/no-unused-vars
const { pageSize, nextToken } = input;

const locations = parseBuckets({
buckets,
tokens: !!tokens,
identityId: identityId!,
userGroup: (userGroups as any)[0], // TODO: fix this edge case
});

return { locations };
};
};

const getPermissions = (
accessRule: Record<string, string[]>,
token: boolean,
groups?: string,
) => {
if (!token) {
return {
permission: accessRule.guest,
};
}
if (groups) {
const selectedKey = Object.keys(accessRule).find(access =>
access.includes(groups),
);

return {
permission: selectedKey
? accessRule[selectedKey]
: accessRule.authenticated,
};
}

return {
permission: accessRule.authenticated,
};
};

const parseBuckets = ({
buckets,
tokens,
identityId,
userGroup,
}: {
buckets: Record<string, BucketInfo>;
tokens: boolean;
identityId: string;
userGroup: string;
}): Location[] => {
const locations: Location[] = [];

for (const [, bucketInfo] of Object.entries(buckets)) {
const { bucketName, paths } = bucketInfo;
for (const [path, accessRules] of Object.entries(paths)) {
// eslint-disable-next-line no-template-curly-in-string
if (tokens && path.includes('${cognito-identity.amazonaws.com:sub}')) {
locations.push({
type: 'PREFIX', // TODO: update logic to include prefix/object
permission: accessRules.entityidentity,
scope: {
bucketName,
path: path.replace(
// eslint-disable-next-line no-template-curly-in-string
'${cognito-identity.amazonaws.com:sub}',
identityId,
),
},
});
}
const location: Location = {
type: 'PREFIX',
...getPermissions(accessRules, tokens, userGroup),
scope: { bucketName, path },
};
if (location.permission) locations.push(location);
}
}

return locations;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { CredentialsProvider, ListLocations } from '../types';
import { listCallerAccessGrants } from '../apis/listCallerAccessGrants';

interface CreateListLocationsHandlerInput {
accountId: string;
credentialsProvider: CredentialsProvider;
region: string;
}

export const createListLocationsHandler = (
handlerInput: CreateListLocationsHandlerInput,
): ListLocations => {
return async function listLocations(input = {}) {
const result = await listCallerAccessGrants({ ...input, ...handlerInput });

return result;
};
};
1 change: 1 addition & 0 deletions packages/storage/src/storageBrowser/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export {
createManagedAuthConfigAdapter,
CreateManagedAuthConfigAdapterInput,
} from './managedAuthConfigAdapter';
export { createAmplifyAuthConfigAdapter } from './amplifyAuthConfigAdapter/createAmplifyAuthConfigAdapter';
export {
GetLocationCredentials,
ListLocations,
Expand Down
12 changes: 12 additions & 0 deletions packages/storage/src/storageBrowser/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,18 @@ export type ListLocations = (
input?: ListLocationsInput,
) => Promise<ListLocationsOutput>;

export type ListPaths = (input?: ListLocationsInput) => Promise<{
locations: {
type: 'PREFIX';
permission: string[];
scope: {
bucketName: string;
path: string;
};
}[];
nextToken?: string;
}>;

export type GetLocationCredentialsInput = CredentialsLocation;
export type GetLocationCredentialsOutput = LocationCredentials;

Expand Down
Loading