Skip to content
Merged
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
230 changes: 226 additions & 4 deletions extensions/whoami.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import { v4 as uuidv4 } from 'uuid';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { makeActor, type Actor } from '../src/backend/core/actor.ts';
import { runWithContext } from '../src/backend/core/context.ts';
import { configContainer } from '../src/backend/exports.ts';
import {
configContainer,
servicesContainers,
storesContainers,
} from '../src/backend/exports.ts';
import { PuterServer } from '../src/backend/server.ts';
import { setupTestServer } from '../src/backend/testUtil.ts';
import { handleWhoami } from './whoami.ts';
Expand Down Expand Up @@ -133,6 +137,226 @@ describe('whoami extension — handleWhoami', () => {
});
});

describe('the address mail is sent as', () => {
// The handler reads stores through extension.import, which resolves
// against the containers rather than the server's copy.
const stubSeats = (ids: unknown[]) =>
installSeatStub(
{
stores: storesContainers,
services: servicesContainers,
} as never,
ids as number[],
);
const teamStore = () =>
storesContainers.team as NonNullable<typeof storesContainers.team>;

const seed = (
fields: {
email_confirmed?: boolean;
password?: string | null;
username?: string;
} = {},
) => {
const slug = Math.random().toString(36).slice(2, 8);
return server.stores.user.create({
username: `WSend_${slug}`,
uuid: uuidv4(),
password: 'hashedpw',
email: `${slug}@example.com`,
...fields,
});
};

const whoamiAs = async (actor: Actor) => {
const { res, captured } = makeRes();
await runWithContext({ actor }, () => handleWhoami(makeReq(), res));
return captured.body as Record<string, unknown>;
};

const userActor = (user: { uuid: string; id: unknown }) =>
makeActor({ user: { uuid: user.uuid, id: user.id as number } });

const appActorWithEmail = async (user: {
uuid: string;
id: unknown;
}) => {
const app = await (
server.stores.app.create as unknown as (
fields: Record<string, unknown>,
opts: { ownerUserId: number },
) => Promise<{ uid: string; id: number }>
)(
{
name: `ws-${uuidv4()}`,
title: 'Sender',
index_url: `https://${uuidv4()}.example/`,
},
{ ownerUserId: user.id as number },
);
const actor = makeActor({
user: { uuid: user.uuid, id: user.id as number },
app: { uid: app.uid, id: app.id },
});
return {
actor,
grant: () =>
server.services.permission.grantUserAppPermission(
userActor(user),
app.uid,
`user:${user.uuid}:email:read`,
),
};
};

const withTeams = async <T>(run: () => Promise<T>): Promise<T> => {
const before = configContainer.teams_enabled;
configContainer.teams_enabled = true;
try {
return await run();
} finally {
configContainer.teams_enabled = before;
}
};

it("is a seat's own Puter mailbox, whatever its email", async () => {
const seat = await seed({ email_confirmed: true });
stubSeats([seat.id]);
const body = await withTeams(() => whoamiAs(userActor(seat)));
expect(body.senderEmail).toBe(
`${seat.username.toLowerCase()}@puter.email`,
);
expect(body.email).toBe(seat.email);
});

it("is any other account's email once confirmed, and absent before", async () => {
const confirmed = await seed({ email_confirmed: true });
const unconfirmed = await seed();
stubSeats([]);
await withTeams(async () => {
expect((await whoamiAs(userActor(confirmed))).senderEmail).toBe(
confirmed.email,
);
expect(
await whoamiAs(userActor(unconfirmed)),
).not.toHaveProperty('senderEmail');
});
});

it("omits an admin's unconfirmed email as a sender", async () => {
const admin = await seed({
username: 'admin',
email_confirmed: false,
});
const body = await whoamiAs(userActor(admin));
expect(body.email_confirmed).toBe(true);
expect(body).not.toHaveProperty('senderEmail');
});

it('omits the sender when teams is enabled without a seat store', async () => {
const user = await seed({ email_confirmed: true });
expect(storesContainers.team).toBeUndefined();
const body = await withTeams(() => whoamiAs(userActor(user)));
expect(body).not.toHaveProperty('senderEmail');
});

it('reads the linked provider while the seat lookup is pending', async () => {
const user = await seed({ password: null });
stubSeats([]);
const pending = Promise.withResolvers<null>();
vi.spyOn(teamStore(), 'getOrgSeat').mockReturnValue(
pending.promise,
);
const provider = vi.spyOn(
servicesContainers.oidc,
'getLinkedProviderForUser',
);
const response = withTeams(() => whoamiAs(userActor(user)));
try {
await vi.waitFor(() =>
expect(provider).toHaveBeenCalledWith(user.id),
);
} finally {
pending.resolve(null);
await response;
provider.mockRestore();
}
});

it('treats nobody as a seat where teams is off', async () => {
const seat = await seed();
stubSeats([seat.id]);
expect(await whoamiAs(userActor(seat))).not.toHaveProperty(
'senderEmail',
);
});

it('reaches an app with the email grant, and only then reads the seat', async () => {
const seat = await seed();
stubSeats([seat.id]);
const lookup = vi.spyOn(teamStore(), 'getOrgSeat');
const { actor, grant } = await appActorWithEmail(seat);

const before = await withTeams(() => whoamiAs(actor));
expect(before).not.toHaveProperty('senderEmail');
expect(lookup).not.toHaveBeenCalled();

await grant();
const after = await withTeams(() => whoamiAs(actor));
expect(after.senderEmail).toBe(
`${seat.username.toLowerCase()}@puter.email`,
);
// Still not the seat's team.
expect(after).not.toHaveProperty('team');
});

it('uses the loaded row for both the grant and seat lookup', async () => {
const seat = await seed({ email_confirmed: true });
const other = await seed();
stubSeats([seat.id]);
const lookup = vi.spyOn(teamStore(), 'getOrgSeat');
const { actor } = await appActorWithEmail(seat);
const check = vi
.spyOn(servicesContainers.permission, 'check')
.mockImplementation(
async (_actor, key) =>
key === `user:${seat.uuid}:email:read`,
);
try {
await withTeams(async () => {
const denied = await whoamiAs({
...actor,
user: { uuid: seat.uuid, id: other.id },
});
expect(denied).not.toHaveProperty('email');
expect(denied).not.toHaveProperty('senderEmail');
expect(lookup).not.toHaveBeenCalled();
const permitted = await whoamiAs({
...actor,
user: { uuid: other.uuid, id: seat.id },
});
expect(permitted.senderEmail).toBe(
`${seat.username.toLowerCase()}@puter.email`,
);
});
} finally {
check.mockRestore();
}
});

it('is left out when the seat cannot be read', async () => {
const user = await seed({ email_confirmed: true });
stubSeats([]);
const lookup = vi
.spyOn(teamStore(), 'getOrgSeat')
.mockRejectedValue(new Error('cache down'));
const body = await withTeams(() => whoamiAs(userActor(user)));
expect(body).not.toHaveProperty('senderEmail');
expect(body.email).toBe(user.email);
expect(lookup).toHaveBeenCalledTimes(1);
});
});

it('returns 401 when no actor is on the context', async () => {
const { res, captured } = makeRes();

Expand Down Expand Up @@ -186,9 +410,7 @@ describe('whoami extension — handleWhoami', () => {

const whoamiAs = async (actor: Actor) => {
const { res, captured } = makeRes();
await runWithContext({ actor }, () =>
handleWhoami(makeReq(), res),
);
await runWithContext({ actor }, () => handleWhoami(makeReq(), res));
return captured;
};

Expand Down
70 changes: 59 additions & 11 deletions extensions/whoami.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Context } from '@heyputer/backend/src/core';
import type { OrgSeatRow } from '@heyputer/backend/src/core/teams.js';
import { extension } from '@heyputer/backend/src/extensions';
import { puterEmailAddressesOf } from '@heyputer/backend/src/services/email/mailbox.js';
import {
buildUserDetails,
scrubSensitive,
Expand All @@ -25,6 +27,35 @@ const APP_VISIBLE_LISTENER_KEYS: ReadonlySet<string> = new Set([
'paid_storage',
]);

/**
* The account's team seat; null when teams is off, undefined when the read
* failed.
*/
const readOrgSeat = async (
userId: number,
): Promise<OrgSeatRow | null | undefined> => {
if (extension.config.teams_enabled !== true) return null;
try {
return await stores.team?.getOrgSeat(userId);
} catch (error) {
console.warn('[whoami] team lookup failed:', error);
return undefined;
}
};

/**
* The address mail sent in the account's name should use. A seat's email is its
* team's claim, so a seat sends as its own Puter mailbox; any other account as
* its email, once confirmed.
*/
const senderEmailOf = (
user: UserRow,
seat: OrgSeatRow | null,
): string | null => {
if (seat) return puterEmailAddressesOf(user.username)[0];
return user.email_confirmed && user.email ? user.email : null;
};

export const handleWhoami = async (
req: Request,
res: Response,
Expand All @@ -47,7 +78,10 @@ export const handleWhoami = async (
}
};
// Started beside the row read: the actor carries the row's uuid.
const emailCheck = isUser ? null : canReadEmail(actor.user.uuid);
const emailCheck = isUser
? Promise.resolve(true)
: canReadEmail(actor.user.uuid);
const userSeat = isUser ? readOrgSeat(actor.user.id) : null;
// Token auth loaded this request's row already; `hasPassword` marks an
// actor built from it.
const user =
Expand All @@ -59,21 +93,34 @@ export const handleWhoami = async (
return;
}

const details = await buildUserDetails(
user,
{ config: extension.config, clients, stores, services },
{ isUser },
);
const emailReadable =
isUser || user.uuid === actor.user.uuid
? emailCheck
: canReadEmail(user.uuid);
const seatRead =
userSeat ??
emailReadable.then((readable) =>
readable ? readOrgSeat(user.id) : undefined,
);
const [details, seat] = await Promise.all([
buildUserDetails(
user,
{ config: extension.config, clients, stores, services },
{ isUser, orgSeat: userSeat ?? undefined },
),
seatRead,
]);
if (seat !== undefined) {
const senderEmail = senderEmailOf(user, seat);
if (senderEmail) details.senderEmail = senderEmail;
}
details.human_readable_age = user.timestamp
? timeago.format(new Date(user.timestamp as string))
: null;

// Strip sensitive fields for app actors
if (!isUser) {
const emailReadable = await (user.uuid === actor.user.uuid
? emailCheck
: canReadEmail(user.uuid));
if (!emailReadable) {
if (!(await emailReadable)) {
delete details.email;
delete details.unconfirmed_email;
}
Expand Down Expand Up @@ -114,7 +161,8 @@ export const handleWhoami = async (
}

const subscription = details.subscription as
{ offering?: Record<string, unknown> } | undefined;
| { offering?: Record<string, unknown> }
| undefined;
if (subscription?.offering) {
delete subscription.offering.group;
delete subscription.offering.benefits;
Expand Down
18 changes: 18 additions & 0 deletions src/backend/core/http/middleware/authProbe.bench.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { makeActor } from '../../actor.js';

describe('auth', () => {
let appToken = '';
let passwordlessAppToken = '';

const seed = async (env: BenchEnv) => {
const owner = await env.server.stores.user.getByUsername(
Expand All @@ -21,6 +22,16 @@ describe('auth', () => {
makeActor({ user: owner! }),
app.uid,
);
const passwordless = await env.server.stores.user.create({
username: 'auth-bench-passwordless',
uuid: crypto.randomUUID(),
password: null,
email: 'auth-bench@example.com',
});
passwordlessAppToken = await env.server.services.auth.getUserAppToken(
makeActor({ user: passwordless }),
app.uid,
);
};

const env = useBenchEnv({ seed });
Expand All @@ -41,6 +52,13 @@ describe('auth', () => {
await env.request('/whoami', { token: appToken });
});

env.scenario(
'whoami with an app token for a passwordless account',
async () => {
await env.request('/whoami', { token: passwordlessAppToken });
},
);

env.scenario('log in with a password', async () => {
const { username, password } = env.users.other;
const response = await fetch(new URL('/login', env.origin), {
Expand Down
Loading
Loading