-
-
Notifications
You must be signed in to change notification settings - Fork 151
fix: tenant s3 credentials fixes and refactor #668
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
Open
itslenny
wants to merge
1
commit into
master
Choose a base branch
from
fix/s3-credential-cache-notify-fix
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
21 changes: 21 additions & 0 deletions
21
migrations/multitenant/0017-tenants-s3-credentials-fix-notify-key.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
CREATE OR REPLACE FUNCTION tenants_s3_credentials_update_notify_trigger () | ||
RETURNS TRIGGER | ||
AS $$ | ||
BEGIN | ||
PERFORM | ||
pg_notify('tenants_s3_credentials_update', '"' || NEW.tenant_id || ':' || NEW.access_key || '"'); | ||
RETURN NULL; | ||
END; | ||
$$ | ||
LANGUAGE plpgsql; | ||
|
||
CREATE OR REPLACE FUNCTION tenants_s3_credentials_delete_notify_trigger () | ||
RETURNS TRIGGER | ||
AS $$ | ||
BEGIN | ||
PERFORM | ||
pg_notify('tenants_s3_credentials_update', '"' || OLD.tenant_id || ':' || OLD.access_key || '"'); | ||
RETURN NULL; | ||
END; | ||
$$ | ||
LANGUAGE plpgsql; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from './manager' |
126 changes: 126 additions & 0 deletions
126
src/internal/database/s3-credentials-manager/manager.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,126 @@ | ||
import crypto from 'node:crypto' | ||
import { LRUCache } from 'lru-cache' | ||
import objectSizeOf from 'object-sizeof' | ||
import { S3Credentials, S3CredentialsManagerStore, S3CredentialsRaw } from './store' | ||
import { createMutexByKey } from '@internal/concurrency' | ||
import { ERRORS } from '@internal/errors' | ||
import { getConfig } from '../../../config' | ||
import { decrypt, encrypt } from '@internal/auth' | ||
import { PubSubAdapter } from '@internal/pubsub' | ||
|
||
const TENANTS_S3_CREDENTIALS_UPDATE_CHANNEL = 'tenants_s3_credentials_update' | ||
|
||
const tenantS3CredentialsCache = new LRUCache<string, S3Credentials>({ | ||
maxSize: 1024 * 1024 * 50, // 50MB | ||
ttl: 1000 * 60 * 60, // 1 hour | ||
sizeCalculation: (value) => objectSizeOf(value), | ||
updateAgeOnGet: true, | ||
allowStale: false, | ||
}) | ||
|
||
const s3CredentialsMutex = createMutexByKey<S3Credentials>() | ||
|
||
export class S3CredentialsManager { | ||
private dbServiceRole: string | ||
|
||
constructor(private storage: S3CredentialsManagerStore) { | ||
const { dbServiceRole } = getConfig() | ||
this.dbServiceRole = dbServiceRole | ||
} | ||
|
||
/** | ||
* Keeps the in memory config cache up to date | ||
*/ | ||
async listenForTenantUpdate(pubSub: PubSubAdapter): Promise<void> { | ||
await pubSub.subscribe(TENANTS_S3_CREDENTIALS_UPDATE_CHANNEL, (cacheKey) => { | ||
tenantS3CredentialsCache.delete(cacheKey) | ||
}) | ||
} | ||
|
||
/** | ||
* Create S3 Credential for a tenant | ||
* @param tenantId | ||
* @param data | ||
*/ | ||
async createS3Credentials( | ||
tenantId: string, | ||
data: { description: string; claims?: S3Credentials['claims'] } | ||
) { | ||
const existingCount = await this.countS3Credentials(tenantId) | ||
|
||
if (existingCount >= 50) { | ||
throw ERRORS.MaximumCredentialsLimit() | ||
} | ||
|
||
const accessKey = crypto.randomBytes(32).toString('hex').slice(0, 32) | ||
const secretKey = crypto.randomBytes(64).toString('hex').slice(0, 64) | ||
|
||
if (data.claims) { | ||
delete data.claims.iss | ||
delete data.claims.issuer | ||
delete data.claims.exp | ||
delete data.claims.iat | ||
} | ||
|
||
const claims = { | ||
...(data.claims || {}), | ||
role: data.claims?.role ?? this.dbServiceRole, | ||
issuer: `supabase.storage.${tenantId}`, | ||
sub: data.claims?.sub, | ||
} | ||
|
||
const id = await this.storage.insert(tenantId, { | ||
description: data.description, | ||
claims, | ||
accessKey, | ||
secretKey: encrypt(secretKey), | ||
}) | ||
|
||
return { | ||
id, | ||
access_key: accessKey, | ||
secret_key: secretKey, | ||
} | ||
} | ||
|
||
async getS3CredentialsByAccessKey(tenantId: string, accessKey: string): Promise<S3Credentials> { | ||
const cacheKey = `${tenantId}:${accessKey}` | ||
const cachedCredentials = tenantS3CredentialsCache.get(cacheKey) | ||
|
||
if (cachedCredentials) { | ||
return cachedCredentials | ||
} | ||
|
||
return s3CredentialsMutex(cacheKey, async () => { | ||
const cachedCredentials = tenantS3CredentialsCache.get(cacheKey) | ||
|
||
if (cachedCredentials) { | ||
return cachedCredentials | ||
} | ||
|
||
const data = await this.storage.getOneByAccessKey(tenantId, accessKey) | ||
|
||
if (!data) { | ||
throw ERRORS.MissingS3Credentials() | ||
} | ||
|
||
data.secretKey = decrypt(data.secretKey) | ||
|
||
tenantS3CredentialsCache.set(cacheKey, data) | ||
|
||
return data | ||
}) | ||
} | ||
|
||
deleteS3Credential(tenantId: string, credentialId: string): Promise<number> { | ||
return this.storage.delete(tenantId, credentialId) | ||
} | ||
|
||
listS3Credentials(tenantId: string): Promise<S3CredentialsRaw[]> { | ||
return this.storage.list(tenantId) | ||
} | ||
|
||
async countS3Credentials(tenantId: string) { | ||
return this.storage.count(tenantId) | ||
} | ||
} |
59 changes: 59 additions & 0 deletions
59
src/internal/database/s3-credentials-manager/store-knex.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
import { Knex } from 'knex' | ||
import { | ||
S3Credentials, | ||
S3CredentialsManagerStore, | ||
S3CredentialsRaw, | ||
S3CredentialWithDescription, | ||
} from './store' | ||
|
||
export class S3CredentialsManagerStoreKnex implements S3CredentialsManagerStore { | ||
constructor(private knex: Knex) {} | ||
|
||
async insert(tenantId: string, credential: S3CredentialWithDescription): Promise<string> { | ||
const credentials = await this.knex | ||
.table('tenants_s3_credentials') | ||
.insert({ | ||
tenant_id: tenantId, | ||
description: credential.description, | ||
access_key: credential.accessKey, | ||
secret_key: credential.secretKey, | ||
claims: JSON.stringify(credential.claims), | ||
}) | ||
.returning('id') | ||
return credentials[0].id | ||
} | ||
|
||
list(tenantId: string): Promise<S3CredentialsRaw[]> { | ||
return this.knex | ||
.table('tenants_s3_credentials') | ||
.select<S3CredentialsRaw[]>('id', 'description', 'access_key', 'created_at') | ||
.where('tenant_id', tenantId) | ||
.orderBy('created_at', 'asc') | ||
} | ||
|
||
getOneByAccessKey(tenantId: string, accessKey: string): Promise<S3Credentials> { | ||
return this.knex | ||
.table('tenants_s3_credentials') | ||
.select({ accessKey: 'access_key', secretKey: 'secret_key', claims: 'claims' }) | ||
.where('tenant_id', tenantId) | ||
.where('access_key', accessKey) | ||
.first() | ||
} | ||
|
||
async count(tenantId: string): Promise<number> { | ||
const data = await this.knex | ||
.table('tenants_s3_credentials') | ||
.count<{ count: number }>('id') | ||
.where('tenant_id', tenantId) | ||
.first() | ||
return Number(data?.count || 0) | ||
} | ||
|
||
delete(tenantId: string, credentialId: string): Promise<number> { | ||
return this.knex | ||
.table('tenants_s3_credentials') | ||
.where('tenant_id', tenantId) | ||
.where('id', credentialId) | ||
.delete() | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
export interface S3Credentials { | ||
accessKey: string | ||
secretKey: string | ||
claims: { role: string; sub?: string; [key: string]: unknown } | ||
} | ||
|
||
export interface S3CredentialWithDescription extends S3Credentials { | ||
description: string | ||
} | ||
|
||
export interface S3CredentialsRaw { | ||
id: string | ||
description: string | ||
access_key: string | ||
created_at: string | ||
} | ||
|
||
export interface S3CredentialsManagerStore { | ||
/** | ||
* Inserts a new credential and returns the id | ||
* | ||
* @param tenantId | ||
*/ | ||
insert(tenantId: string, credential: S3CredentialWithDescription): Promise<string> | ||
|
||
/** | ||
* List all credentials for the specified tenant | ||
* Returns data in the database style (snake case) format because the endpoint is expected to return data in this format | ||
* | ||
* @param tenantId | ||
*/ | ||
list(tenantId: string): Promise<S3CredentialsRaw[]> | ||
|
||
/** | ||
* Get one credential for the specified tenant / access key | ||
* | ||
* @param tenantId | ||
* @param accessKey | ||
*/ | ||
getOneByAccessKey(tenantId: string, accessKey: string): Promise<S3Credentials> | ||
|
||
/** | ||
* Gets the count of credentials for the specified tenant | ||
* | ||
* @param tenantId | ||
*/ | ||
count(tenantId: string): Promise<number> | ||
|
||
/** | ||
* Deletes a credential and returns the count of items deleted | ||
* | ||
* @param tenantId | ||
* @param credentialId | ||
*/ | ||
delete(tenantId: string, credentialId: string): Promise<number> | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we move this to
storage/protocols/s3/credentials-manager.ts