Skip to content

Commit

Permalink
fix(user): mock auth to simulate auth0 userId
Browse files Browse the repository at this point in the history
  • Loading branch information
baktun14 committed Feb 11, 2025
1 parent bb8bc84 commit 80563cc
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 11 deletions.
3 changes: 2 additions & 1 deletion apps/api/src/auth/services/ability/ability.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ export class AbilityService {
{ action: ["create", "read", "sign"], subject: "UserWallet", conditions: { userId: "${user.id}" } },
{ action: "read", subject: "User", conditions: { id: "${user.id}" } },
{ action: "read", subject: "StripePrice" },
{ action: "create", subject: "VerificationEmail", conditions: { id: "${user.id}" } }
{ action: "create", subject: "VerificationEmail", conditions: { id: "${user.id}" } },
{ action: "manage", subject: "DeploymentSetting", conditions: { userId: "${user.id}" } }
],
REGULAR_PAYING_USER: [
{ action: ["create", "read", "sign"], subject: "UserWallet", conditions: { userId: "${user.id}" } },
Expand Down
79 changes: 69 additions & 10 deletions apps/api/test/functional/api-key.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import { container } from "tsyringe";
import { app } from "@src/app";
import { ApiKeyRepository } from "@src/auth/repositories/api-key/api-key.repository";
import { ApiKeyGeneratorService } from "@src/auth/services/api-key/api-key-generator.service";
import { AuthInterceptor } from "@src/auth/services/auth.interceptor";
import { AuthTokenService } from "@src/auth/services/auth-token/auth-token.service";
import { CoreConfigService } from "@src/core/services/core-config/core-config.service";
import { UserRepository } from "@src/user/repositories/user/user.repository";

import { ApiKeySeeder } from "@test/seeders/api-key.seeder";
import { DbTestingService } from "@test/services/db-testing.service";
Expand All @@ -20,14 +23,46 @@ describe("API Keys", () => {
const dbService = container.resolve(DbTestingService);
const walletService = new WalletTestingService(app);
const apiKeyRepository = container.resolve(ApiKeyRepository);
const userRepository = container.resolve(UserRepository);
const authTokenService = container.resolve(AuthTokenService);
const authInterceptor = container.resolve(AuthInterceptor);
let config: jest.Mocked<CoreConfigService>;
let apiKeyGenerator: ApiKeyGeneratorService;

// TODO: This is a hack to avoid implementing proper auth0 mocking
// Refactor once the proper auth0 mocking is implemented
// https://github.com/akash-network/console/issues/552
async function createTestUser(trial = false) {
const { user, token } = await walletService.createUserAndWallet();
const userWithId = { ...user, userId: faker.string.uuid() };

jest.spyOn(userRepository, "findByUserId").mockImplementation(async id => {
if (id === userWithId.userId) {
return {
...userWithId,
trial,
userWallets: { isTrialing: trial }
};
}
return undefined;
});

jest.spyOn(authInterceptor as any, "getValidUserId").mockImplementation(async () => {
return Promise.resolve(userWithId.userId);
});

if (!trial) {
// Mock AuthTokenService to return undefined for anonymous tokens
jest.spyOn(authTokenService, "getValidUserId").mockResolvedValue(undefined);
}

return { user: userWithId, token };
}

beforeEach(async () => {
config = stub<CoreConfigService>({ get: jest.fn() });
config.get.mockReturnValue("test");
apiKeyGenerator = new ApiKeyGeneratorService(config);

await dbService.cleanAll();
});

Expand All @@ -38,7 +73,7 @@ describe("API Keys", () => {
});

it("should return empty array if no API keys found", async () => {
const { token } = await walletService.createUserAndWallet();
const { token } = await createTestUser();

const response = await app.request("/v1/api-keys", {
headers: { authorization: `Bearer ${token}` }
Expand All @@ -49,7 +84,8 @@ describe("API Keys", () => {
});

it("should not return other user's API keys", async () => {
const [{ user: user1 }, { token: token2 }] = await Promise.all([walletService.createUserAndWallet(), walletService.createUserAndWallet()]);
const { user: user1 } = await createTestUser();
const { token: token2 } = await createTestUser();

const key1 = ApiKeySeeder.create({
userId: user1.id,
Expand All @@ -71,7 +107,7 @@ describe("API Keys", () => {
});

it("should return list of API keys with obfuscated keys", async () => {
const { token, user } = await walletService.createUserAndWallet();
const { token, user } = await createTestUser();
const apiKey = apiKeyGenerator.generateApiKey();
const hashedKey = await apiKeyGenerator.hashApiKey(apiKey);
const obfuscatedKey = apiKeyGenerator.obfuscateApiKey(apiKey);
Expand Down Expand Up @@ -127,7 +163,7 @@ describe("API Keys", () => {
});

it("should return 404 if API key not found", async () => {
const { token } = await walletService.createUserAndWallet();
const { token } = await createTestUser();
const keyId = faker.string.uuid();

const response = await app.request(`/v1/api-keys/${keyId}`, {
Expand All @@ -142,7 +178,7 @@ describe("API Keys", () => {
});

it("should return API key details with obfuscated key", async () => {
const { token, user } = await walletService.createUserAndWallet();
const { token, user } = await createTestUser();
const apiKey = apiKeyGenerator.generateApiKey();
const hashedKey = await apiKeyGenerator.hashApiKey(apiKey);
const obfuscatedKey = apiKeyGenerator.obfuscateApiKey(apiKey);
Expand Down Expand Up @@ -187,7 +223,7 @@ describe("API Keys", () => {
});

it("should create API key and return full key once", async () => {
const { token } = await walletService.createUserAndWallet();
const { token } = await createTestUser();
const futureDate = new Date();
futureDate.setFullYear(futureDate.getFullYear() + 1);

Expand Down Expand Up @@ -220,7 +256,7 @@ describe("API Keys", () => {
});

it("should reject API key creation with past expiration date", async () => {
const { token } = await walletService.createUserAndWallet();
const { token } = await createTestUser();
const pastDate = new Date();
pastDate.setFullYear(pastDate.getFullYear() - 1); // 1 year ago

Expand Down Expand Up @@ -251,6 +287,29 @@ describe("API Keys", () => {
]
});
});

it("should reject API key creation for trial users", async () => {
const { token } = await createTestUser(true);

const response = await app.request("/v1/api-keys", {
method: "POST",
headers: {
authorization: `Bearer ${token}`,
"content-type": "application/json"
},
body: JSON.stringify({
data: {
name: "Test key"
}
})
});

expect(response.status).toBe(403);
expect(await response.json()).toEqual({
error: "ForbiddenError",
message: "Forbidden"
});
});
});

describe("PATCH /v1/api-keys/{id}", () => {
Expand All @@ -270,7 +329,7 @@ describe("API Keys", () => {
});

it("should update API key", async () => {
const { token, user } = await walletService.createUserAndWallet();
const { token, user } = await createTestUser();
const apiKey = apiKeyGenerator.generateApiKey();
const hashedKey = await apiKeyGenerator.hashApiKey(apiKey);
const obfuscatedKey = apiKeyGenerator.obfuscateApiKey(apiKey);
Expand Down Expand Up @@ -320,7 +379,7 @@ describe("API Keys", () => {
});

it("should delete API key", async () => {
const { token, user } = await walletService.createUserAndWallet();
const { token, user } = await createTestUser();
const apiKey = apiKeyGenerator.generateApiKey();
const hashedKey = await apiKeyGenerator.hashApiKey(apiKey);
const obfuscatedKey = apiKeyGenerator.obfuscateApiKey(apiKey);
Expand Down

0 comments on commit 80563cc

Please sign in to comment.