Skip to content

Commit

Permalink
Merge pull request #294 from zallo-labs/Z-346-invalid-cloud-approver-…
Browse files Browse the repository at this point in the history
…name

Z 346 invalid cloud approver name
  • Loading branch information
hbriese authored Aug 23, 2024
2 parents 09a418b + e76872e commit 6907e41
Show file tree
Hide file tree
Showing 13 changed files with 52 additions and 41 deletions.
10 changes: 10 additions & 0 deletions api/dbschema/migrations/00008-m13ngaz.edgeql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
CREATE MIGRATION m13ngazbt3dkkbegsr7e2te4y7j4jltf56szjupnmb3ngzd6yq33zq
ONTO m15qj3htiny7zuqceuvj46wrm7yza5xyqmfuadsywsbc6tvh6vb34a
{
ALTER SCALAR TYPE default::BoundedStr {
DROP CONSTRAINT std::regexp(r'^(?![0oO][xX])[^\n\t]{3,50}$');
};
ALTER SCALAR TYPE default::BoundedStr {
CREATE CONSTRAINT std::regexp(r'^(?![0oO][xX])[^\n\t]{2,70}$');
};
};
2 changes: 1 addition & 1 deletion api/dbschema/scalars.esdl
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ module default {
};

scalar type BoundedStr extending str {
constraint regexp(r'^(?![0oO][xX])[^\n\t]{3,50}$');
constraint regexp(r'^(?![0oO][xX])[^\n\t]{2,70}$');
}

scalar type Bytes extending str {
Expand Down
2 changes: 0 additions & 2 deletions api/src/core/context/context.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ import { AsyncLocalStorage } from 'async_hooks';
import { uuid } from 'edgedb/dist/codecs/ifaces';
import { Address, UAddress, UUID } from 'lib';
import { GqlContext } from '~/core/apollo/ctx';
import { type Client as DatabaseClient } from 'edgedb';

export interface Context {
afterRequestHooks: AfterRequestHook[];
user?: UserContext;
db?: DatabaseClient;
}

export interface UserContext {
Expand Down
18 changes: 11 additions & 7 deletions api/src/core/database/database.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,11 @@ export class DatabaseService implements OnModuleInit {
const reqCtx = getContextUnsafe();
if (!reqCtx?.user) return this.DANGEROUS_superuserClient;

reqCtx.db ??= this.__client.withGlobals({
return this.__client.withGlobals({
current_accounts: reqCtx.user.accounts.map((a) => a.id),
current_approver_address: reqCtx.user.approver,
// current_user_id: reqCtx.user.id,
} satisfies Globals);

return reqCtx.db;
}

private async run<R>(f: () => Promise<R>, name = 'inline'): Promise<R> {
Expand All @@ -74,8 +72,15 @@ export class DatabaseService implements OnModuleInit {
getExpr: (params: paramsToParamExprs<Params>) => Expr,
params: paramsToParamArgs<Params>,
) {
const expression = e.params(paramsDef, getExpr as any);
return this.run(() => expression.run(this.client, params as any)) as Promise<$infer<Expr>>;
try {
const expression = e.params(paramsDef, getExpr as any);
return (await this.run(() => expression.run(this.client, params as any))) as Promise<
$infer<Expr>
>;
} catch (e) {
if (e instanceof EdgeDBError) Sentry.setExtra('EdgeQL Params', params);
throw e;
}
}

async queryWith2<
Expand All @@ -86,8 +91,7 @@ export class DatabaseService implements OnModuleInit {
params: paramsToParamArgs<Params>,
getExpr: (params: paramsToParamExprs<Params>) => Expr,
) {
const expression = e.params(paramsDef, getExpr as any);
return this.run(() => expression.run(this.client, params as any)) as Promise<$infer<Expr>>;
return this.queryWith(paramsDef, getExpr, params);
}

async exec<F extends (client: Executor, args: any) => Promise<any>>(
Expand Down
1 change: 1 addition & 0 deletions api/src/core/sentry/sentry.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export class SentryInterceptor implements NestInterceptor {

scope.setExtra('exceptionData', JSON.stringify(exception, null, 2));
this.addContextExceptionMetadata(scope, context);
scope.setExtra('userContext', getContextUnsafe()?.user);

Sentry.captureException(exception);
},
Expand Down
17 changes: 8 additions & 9 deletions api/src/feat/accounts/accounts.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { AccountEvent } from './accounts.model';
import { PolicyInput } from '../policies/policies.input';
import { utils as zkUtils } from 'zksync-ethers';
import { toHex } from 'viem';
import { insertAccount } from './insert-account.query';

const accountTrigger = (account: UAddress) => `account.updated:${account}`;
const accountApproverTrigger = (approver: Address) => `account.updated:approver:${approver}`;
Expand Down Expand Up @@ -148,15 +149,13 @@ export class AccountsService {
);

await this.db.transaction(async () => {
await this.db.query(
e.insert(e.Account, {
id,
address,
name,
implementation,
initialization: { salt, bytecodeHash, aaVersion: 1 },
}),
);
await this.db.exec(insertAccount, {
id,
address,
name,
implementation,
initialization: { salt, bytecodeHash, aaVersion: 1 },
});

await this.policies.propose(
{
Expand Down
13 changes: 5 additions & 8 deletions api/src/feat/auth/accounts.cache.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,9 @@ export class AccountsCacheService implements OnModuleInit {
accounts: JSON.parse(cachedAccounts) as UserAccountContext[],
};

const { user } = await this.db.queryWith(
const { user } = await this.db.queryWith2(
{ approver: e.Address },
{ approver },
({ approver }) =>
e.select(
e.insert(e.Approver, { address: approver }).unlessConflict((a) => ({
Expand All @@ -71,7 +72,6 @@ export class AccountsCacheService implements OnModuleInit {
},
}),
),
{ approver },
);

const accounts = user.accounts.map(
Expand Down Expand Up @@ -99,14 +99,11 @@ export class AccountsCacheService implements OnModuleInit {
if (!getUserCtx().accounts.find((a) => a.id === account.id))
getUserCtx().accounts.push(account);

const user = await this.db.queryWith(
const user = await this.db.queryWith2(
{ approver: e.Address },
({ approver }) =>
e.select(e.Approver, () => ({
filter_single: { address: approver },
user: { id: true },
})).user.id,
{ approver },
({ approver }) =>
e.select(e.Approver, () => ({ filter_single: { address: approver } })).user.id,
);

if (user) {
Expand Down
5 changes: 2 additions & 3 deletions api/src/feat/policies/existing-policies.edgeql
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
with account := (select Account filter .address = <UAddress>$account),
keys := array_unpack(<array<uint16>>$policyKeys)
select Policy {
select account.<account[is Policy] {
key,
name,
approvers: { address },
Expand All @@ -26,5 +26,4 @@ select Policy {
},
allowMessages,
delay,
} filter .account = account and .key in keys and
(.isDraft if exists .draft else .isLatest)
} filter .key in keys and (.isDraft if exists .draft else .isLatest)
5 changes: 2 additions & 3 deletions api/src/feat/policies/existing-policies.query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export function existingPolicies(client: Executor, args: ExistingPoliciesArgs):
return client.query(`\
with account := (select Account filter .address = <UAddress>$account),
keys := array_unpack(<array<uint16>>$policyKeys)
select Policy {
select account.<account[is Policy] {
key,
name,
approvers: { address },
Expand All @@ -71,7 +71,6 @@ select Policy {
},
allowMessages,
delay,
} filter .account = account and .key in keys and
(.isDraft if exists .draft else .isLatest)`, args);
} filter .key in keys and (.isDraft if exists .draft else .isLatest)`, args);

}
1 change: 1 addition & 0 deletions api/src/feat/transfers/insert-transfer.edgeql
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,6 @@ with accountAddress := <UAddress>$account,
select transfer {
id,
internal,
fee,
accountUsers := .account.approvers.user.id
}
2 changes: 1 addition & 1 deletion app/src/components/transaction/TransactionDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export function TransactionDetails(props: TransactionDetailsProps) {
}
trailing={
<Percent
value={Number((BigInt(t.result.gasUsed) * 10000n) / BigInt(t.gasLimit)) / 100}
value={Number((BigInt(t.result.gasUsed ?? 0) * 10000n) / BigInt(t.gasLimit)) / 100}
/>
}
/>
Expand Down
11 changes: 7 additions & 4 deletions app/src/hooks/cloud/useGetCloudApprover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { useGetCloudApproverQuery } from '~/api/__generated__/useGetCloudApprove
import { signAuthHeaders } from '~/api/auth-manager';
import { UpdateApproverInput } from '~/api/__generated__/useGetCloudApproverMutation.graphql';
import { withHeaders } from '~/api/network/auth';
import { zBoundStr } from '~/lib/zod';

const PK_PATH = '/approver.private-key';
const SCOPE = CloudStorageScope.AppData;
Expand Down Expand Up @@ -84,9 +85,7 @@ export function useGetCloudApprover() {
await fetchQuery<useGetCloudApproverQuery>(
environment,
Query,
{
approver: approver.address,
},
{ approver: approver.address },
{ networkCacheConfig: withHeaders(authHeaders) },
).toPromise()
)?.approver.details;
Expand All @@ -95,7 +94,11 @@ export function useGetCloudApprover() {
{
input: {
address: approver.address,
name: !e?.name ? details?.name : undefined,
name: !e?.name
? zBoundStr().safeParse(
details?.name?.slice(0, zBoundStr().maxLength ?? undefined),
)
: undefined,
cloud: !e?.cloud ? details?.cloud : undefined,
},
},
Expand Down
6 changes: 3 additions & 3 deletions app/src/lib/zod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,9 @@ export function zBool() {
export function zBoundStr() {
return z
.string()
.min(3)
.max(50)
.regex(/(?![0oO][xX])[^\n\t]{3,50}$/, 'Must not start with 0x');
.min(2)
.max(70)
.regex(/(?![0oO][xX])[^\n\t]{2,70}$/, 'Must not start with 0x');
}

export function zNonEmptyStr() {
Expand Down

0 comments on commit 6907e41

Please sign in to comment.