Skip to content

Commit

Permalink
chore: more fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Nicolas Burtey committed Oct 9, 2023
1 parent 59eeac0 commit 5086bd2
Show file tree
Hide file tree
Showing 18 changed files with 46 additions and 50 deletions.
6 changes: 3 additions & 3 deletions core/api/src/domain/users/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const PhoneNumberRegex = /^\+\d{7,14}$/i // FIXME {7,14} to be refined

const EmailAddressRegex = /^[\w-.+]+@([\w-]+\.)+[\w-]{2,4}$/i

const IdRegex =
const UuidRegex =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i

export const checkedToPhoneNumber = (
Expand Down Expand Up @@ -74,7 +74,7 @@ export const checkedToDeviceId = (
export const checkedToIdentityUsername = (
username: string,
): IdentityUsername | ValidationError => {
if (!username.match(IdRegex)) {
if (!username.match(UuidRegex)) {
return new InvalidIdentityUsername(username)
}
return username as IdentityUsername
Expand All @@ -83,7 +83,7 @@ export const checkedToIdentityUsername = (
export const checkedToIdentityPassword = (
password: string,
): IdentityPassword | ValidationError => {
if (!password.match(IdRegex)) {
if (!password.match(UuidRegex)) {
return new InvalidIdentityPassword(password)
}
return password as IdentityPassword
Expand Down
4 changes: 2 additions & 2 deletions core/api/src/domain/wallets/validation.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { InvalidWalletId } from "@/domain/errors"

const IdRegex =
const UuidRegex =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i

export const WalletIdRegex = IdRegex
export const WalletIdRegex = UuidRegex

export const checkedToWalletId = (walletId: string): WalletId | ValidationError => {
if (!walletId.match(WalletIdRegex)) {
Expand Down
14 changes: 7 additions & 7 deletions core/api/src/graphql/admin/root/mutation/account-update-level.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import AccountDetailPayload from "@/graphql/admin/types/payload/account-detail"
import AccountLevel from "@/graphql/shared/types/scalar/account-level"
import { mapAndParseErrorForGqlResponse } from "@/graphql/error-map"
import { GT } from "@/graphql/index"
import AccountId from "@/graphql/shared/types/scalar/account-id"

const AccountUpdateLevelInput = GT.Input({
name: "AccountUpdateLevelInput",
fields: () => ({
accountId: {
type: GT.NonNull(AccountId),
// FIXME: should be account id
uid: {
type: GT.NonNullID,
},
level: {
type: GT.NonNull(AccountLevel),
Expand All @@ -22,7 +22,7 @@ const AccountUpdateLevelMutation = GT.Field<
GraphQLAdminContext,
{
input: {
accountId: AccountId | Error
uid: string | Error
level: AccountLevel | Error
}
}
Expand All @@ -35,12 +35,12 @@ const AccountUpdateLevelMutation = GT.Field<
input: { type: GT.NonNull(AccountUpdateLevelInput) },
},
resolve: async (_, args) => {
const { accountId, level } = args.input
const { uid, level } = args.input

if (level instanceof Error) return { errors: [{ message: level.message }] }
if (accountId instanceof Error) return { errors: [{ message: accountId.message }] }
if (uid instanceof Error) return { errors: [{ message: uid.message }] }

const account = await Accounts.updateAccountLevel({ accountId, level })
const account = await Accounts.updateAccountLevel({ accountId: uid, level })

if (account instanceof Error) {
return { errors: [mapAndParseErrorForGqlResponse(account)] }
Expand Down
5 changes: 1 addition & 4 deletions core/api/src/graphql/admin/schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@ type AccountDetailPayload {
errors: [Error!]!
}

"""Unique identifier of an account"""
scalar AccountId

enum AccountLevel {
ONE
TWO
Expand All @@ -21,8 +18,8 @@ enum AccountStatus {
}

input AccountUpdateLevelInput {
accountId: AccountId!
level: AccountLevel!
uid: ID!
}

input AccountUpdateStatusInput {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ const getNonUserWalletIds = async ({ usersCollection, walletsCollection }) => {
}

module.exports = {
/* eslint @typescript-eslint/ban-ts-comment: "off" */
// @ts-ignore-next-line no-implicit-any error
async up(db) {
const usersCollection = db.collection("users")
const walletsCollection = db.collection("wallets")
Expand Down Expand Up @@ -96,7 +98,7 @@ module.exports = {
if (txns[0].currency === txns[1].currency) return false

// Compare accountIds to see if self-trade
const accountIdsSet = new Set(txns.map((txn) => txn.AccountId))
const accountIdsSet = new Set(txns.map((txn) => txn.accountId))
if (accountIdsSet.size > 1) return false

// RETURN SELF-TRADE TYPE
Expand Down
10 changes: 6 additions & 4 deletions core/api/src/migrations/20230807205306-add-uuid-to-accounts.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint @typescript-eslint/ban-ts-comment: "off" */
// @ts-nocheck
/* eslint @typescript-eslint/no-var-requires: "off" */
const getUuidByString = require("id-by-string")
const getUuidByString = require("uuid-by-string")

async function migrateAccounts(db, batchSize = 100) {
const cursor = db.collection("accounts").find()
Expand All @@ -11,11 +11,11 @@ async function migrateAccounts(db, batchSize = 100) {
const batchUpdates = []
for (let i = 0; i < batchSize && (await cursor.hasNext()); i++) {
const account = await cursor.next()
const id = account.id || getUuidByString(account._id.toString())
const id = account.uuid || getUuidByString(account._id.toString())
batchUpdates.push({
updateOne: {
filter: { _id: account._id },
update: { $set: { id }, $unset: { id: 1 } },
update: { $set: { id }, $unset: { uuid: 1 } },
},
})
}
Expand All @@ -32,13 +32,15 @@ async function migrateAccounts(db, batchSize = 100) {
}

module.exports = {
/* eslint @typescript-eslint/ban-ts-comment: "off" */
// @ts-ignore-next-line no-implicit-any error
async up(db) {
console.log("Begin migration to add UUIDs to Accounts Schema")
await migrateAccounts(db)
console.log("Migration to add UUIDs to Accounts Schema completed")
},

async down() {
console.log(`Rollback of add id to Account Schema migration not needed`)
console.log(`Rollback of add uuid to Account Schema migration not needed`)
},
}
2 changes: 1 addition & 1 deletion core/api/src/servers/graphql-admin-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ const setGqlAdminContext = async (
}

// can be anon.
// TODO: refactor to remove auth endpoint and make context always carry a id v4 .sub/UserId
// TODO: refactor to remove auth endpoint and make context always carry a uuid v4 .sub/UserId
const auditorId = tokenPayload.sub as UserId

let isEditor = false
Expand Down
4 changes: 2 additions & 2 deletions core/api/src/servers/middlewares/idempotency.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ import { addAttributesToCurrentSpan } from "@/services/tracing"
// Create lock service instance
const lockService = LockService()

const IdRegex =
const UuidRegex =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i

const checkedToIdempotencyKey = (input: string) => {
if (!input.match(IdRegex)) {
if (!input.match(UuidRegex)) {
return new InvalidIdempotencyKeyError(input)
}
return input as IdempotencyKey
Expand Down
8 changes: 4 additions & 4 deletions core/api/src/services/kratos/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ export * from "./identity"
export * from "./totp"
export * from "./schema"

export const IdRegex =
export const UuidRegex =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i

export const checkedToEmailRegistrationId = (
flow: string,
): EmailRegistrationId | ValidationError => {
if (!flow.match(IdRegex)) {
if (!flow.match(UuidRegex)) {
return new InvalidFlowId(flow)
}
return flow as EmailRegistrationId
Expand All @@ -27,14 +27,14 @@ export const checkedToEmailRegistrationId = (
export const checkedToTotpRegistrationId = (
flow: string,
): TotpRegistrationId | ValidationError => {
if (!flow.match(IdRegex)) {
if (!flow.match(UuidRegex)) {
return new InvalidFlowId(flow)
}
return flow as TotpRegistrationId
}

export const checkedToEmailLoginId = (flow: string): EmailLoginId | ValidationError => {
if (!flow.match(IdRegex)) {
if (!flow.match(UuidRegex)) {
return new InvalidFlowId(flow)
}
return flow as EmailLoginId
Expand Down
2 changes: 1 addition & 1 deletion core/api/src/services/mongoose/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ const AccountIpsSchema = new Schema<AccountIpsRecord>({
export const AccountIps = mongoose.model<AccountIpsRecord>("AccountIp", AccountIpsSchema)

AccountIpsSchema.index({
_AccountId: 1,
accountId: 1,
ip: 1,
})

Expand Down
2 changes: 1 addition & 1 deletion core/api/src/services/svix/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export const CallbackService = (config: SvixConfig) => {
const prefixedPayload = prefixObjectKeys(payload, "callback.payload.")
addAttributesToCurrentSpan({
...prefixedPayload,
["callback.AccountId"]: accountId,
["callback.accountId"]: accountId,
["callback.eventType"]: eventType,
})
baseLogger.info({ res }, `message sent successfully to ${accountCallbackId}`)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
query accountDetailsByAccountId($accountId: ID!) {
accountDetailsByAccountId(accountId: $accountId) {
id
uuid
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
query accountDetailsByUserPhone($phone: Phone!) {
accountDetailsByUserPhone(phone: $phone) {
id
uuid
}
}
7 changes: 2 additions & 5 deletions core/api/test/bats/admin.bats
Original file line number Diff line number Diff line change
Expand Up @@ -86,18 +86,15 @@ gql_admin_file() {
exec_admin_graphql $admin_token 'account-details-by-user-phone' "$variables"
id="$(graphql_output '.data.accountDetailsByUserPhone.id')"
[[ "$id" != "null" && "$id" != "" ]] || exit 1
id="$(graphql_output '.data.accountDetailsByUserPhone.id')"
[[ "$id" != "null" && "$id" != "" ]] || exit 1

echo "id: $id"
echo "id: $id"

new_phone="$(random_phone)"
variables=$(
jq -n \
--arg phone "$new_phone" \
--arg AccountId "$id" \
'{input: {phone: $phone, accountId:$AccountId}}'
--arg accountId "$id" \
'{input: {phone: $phone, accountId:$accountId}}'
)

exec_admin_graphql $admin_token 'user-update-phone' "$variables"
Expand Down
4 changes: 2 additions & 2 deletions core/api/test/bats/device-account.bats
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ jwt="eyJhbGciOiJSUzI1NiIsImtpZCI6IjFiOTdiMjIxLWNhMDgtNGViMi05ZDA5LWE1NzcwZmNjZWI
@test "device-account: create" {
token_name="$DEVICE_NAME"

username="$(random_id)"
password="$(random_id)"
username="$(random_uuid)"
password="$(random_uuid)"

if [[ "$(uname)" == "Linux" ]]; then
basic_token="$(echo -n $username:$password | base64 -w 0)"
Expand Down
10 changes: 5 additions & 5 deletions core/api/test/bats/helpers/_common.bash
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ gql_file() {
}

new_idempotency_key() {
random_id
random_uuid
}

exec_graphql() {
Expand Down Expand Up @@ -150,11 +150,11 @@ graphql_output() {
echo $output | jq -r "$@"
}

random_id() {
if [[ -e /proc/sys/kernel/random/id ]]; then
cat /proc/sys/kernel/random/id
random_uuid() {
if [[ -e /proc/sys/kernel/random/uuid ]]; then
cat /proc/sys/kernel/random/uuid
else
idgen
uuidgen
fi
}

Expand Down
10 changes: 5 additions & 5 deletions core/api/test/bats/oathkeeper.bats
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ teardown_file() {

OATHKEEPER_ENDPOINT=${OATHKEEPER_ENDPOINT:-"http://127.0.0.1:4456/decisions/"}

check_is_id() {
id_string=$1
check_is_uuid() {
uuid_string=$1

id_regex='^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
echo $id_string | grep -Eq "$id_regex"
uuid_regex='^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
echo $uuid_string | grep -Eq "$uuid_regex"
}

decode_jwt() {
Expand Down Expand Up @@ -116,5 +116,5 @@ oathkeeper_jwt() {
cache_value 'alice.oath' $jwt

subject=$(decode_jwt "$jwt" 'payload' | jq -r '.sub')
check_is_id "$subject" || exit 1
check_is_uuid "$subject" || exit 1
}
2 changes: 1 addition & 1 deletion core/api/test/bats/public-ln-receive.bats
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ usd_amount=50
}

@test "public-ln-receive: fail to create invoice - nonexistent wallet-id" {
non_existent_wallet_id="$(random_id)"
non_existent_wallet_id="$(random_uuid)"

variables=$(
jq -n \
Expand Down

0 comments on commit 5086bd2

Please sign in to comment.