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
17 changes: 17 additions & 0 deletions apps/api/src/services/agent-email/system-email.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* The transport for SAM's own email (sign-in codes, owner security alerts), resolved the same way
* for every caller: the Cloudflare `AGENT_EMAIL` binding when it exists, otherwise SMTP (`SMTP_*`,
* a self-hosted celld box), otherwise none (`emailTransportKind`). The SMTP timeout setting is
* read only when SMTP is the transport, so a Cloudflare send costs no settings read.
*/
import type { Env } from '../../env';
import { type EmailTransport, emailTransportKind, systemEmailTransportFor } from './provider';
import { getAgentEmailLimits } from './settings';

/** The transport SAM's own email goes out through here, or null when it can send none. */
export async function resolveSystemEmailTransport(env: Env): Promise<EmailTransport | null> {
const kind = emailTransportKind(env);
if (!kind) return null;
const smtpTimeoutMs = kind === 'smtp' ? (await getAgentEmailLimits(env)).smtpTimeoutMs : 0;
return systemEmailTransportFor(env, { smtpTimeoutMs });
}
12 changes: 3 additions & 9 deletions apps/api/src/services/email-sign-in.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,9 @@ import {
} from '../middleware/rate-limit';
import { agentEmailDomain } from './agent-email/address';
import { listSendingSubdomains } from './agent-email/cloudflare-email-api';
import {
type EmailTransportEnv,
emailTransportKind,
systemEmailTransportFor,
} from './agent-email/provider';
import { type EmailTransportEnv, emailTransportKind } from './agent-email/provider';
import { getAgentEmailLimits } from './agent-email/settings';
import { resolveSystemEmailTransport } from './agent-email/system-email';
import { bootstrapOwnerEmail, bootstrapOwnerEstablished } from './bootstrap-owner';

const log = createModuleLogger('email-sign-in');
Expand Down Expand Up @@ -257,10 +254,7 @@ export async function deliverSignInCode(env: Env, email: string, code: string):
log.info('email_sign_in.code_not_sent', { reason: 'no_account' });
return;
}
// The timeout setting is read only where it applies, so a Cloudflare send costs no read.
const smtpTimeoutMs =
emailTransportKind(env) === 'smtp' ? (await getAgentEmailLimits(env)).smtpTimeoutMs : 0;
const transport = systemEmailTransportFor(env, { smtpTimeoutMs });
const transport = await resolveSystemEmailTransport(env);
if (!transport) return;
// The note goes to the mailbox, not into the API response, so the response still reveals
// nothing about which addresses have accounts.
Expand Down
9 changes: 8 additions & 1 deletion apps/api/src/services/gitlab-login-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,13 @@ import type { GitLabOAuthConfig } from './platform-config-oauth';

const log = createModuleLogger('gitlab-login');

const GITLAB_SCOPES = ['read_user', 'api', 'read_repository', 'write_repository'];
/**
* Every scope SAM asks GitLab for, once each. better-auth's GitLab provider prepends its own
* default `read_user` unless `disableDefaultScope` is set, which made the authorize URL ask for
* `read_user` twice (box round R17, D4); the provider below disables that default so this list
* is the whole request.
*/
export const GITLAB_SCOPES = ['read_user', 'api', 'read_repository', 'write_repository'];

const gitlabUserSchema = v.object({
id: v.number(),
Expand Down Expand Up @@ -131,6 +137,7 @@ export function gitLabLoginProvider(env: Env, config: GitLabOAuthConfig): GitLab
clientSecret: config.clientSecret,
issuer: config.host,
scope: GITLAB_SCOPES,
disableDefaultScope: true,
overrideUserInfoOnSignIn: config.identityTrusted,
getUserInfo: (token) => fetchGitLabUserInfo(env, config, token.accessToken),
};
Expand Down
25 changes: 13 additions & 12 deletions apps/api/src/services/security-alerts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
*
* Delivery is best-effort by design. Every entry point schedules work on the request's
* `waitUntil` and returns immediately; nothing here can block, fail or roll back the mutation
* that triggered it. Failures are logged (`security_alert.*`). The sender is the agent email
* send binding sign-in codes already use (`agentEmailSenderFor`); a deployment without it logs
* that triggered it. Failures are logged (`security_alert.*`). The sender is the transport
* sign-in codes use (`resolveSystemEmailTransport`): the Cloudflare `AGENT_EMAIL` binding, or
* SMTP on an install without it (a self-hosted box). A deployment with neither logs
* `security_alert.no_sender` and sends nothing.
*/
import { SYSTEM_USER_ID } from '@simple-agent-manager/shared';
Expand All @@ -22,15 +23,17 @@ import {
resolveActorLabels,
sanitizeLabel,
} from './actor-labels';
import { agentEmailDomain } from './agent-email/address';
import { agentEmailSenderFor } from './agent-email/provider';
import { resolveSystemEmailTransport } from './agent-email/system-email';
import { bootstrapOwnerEmail } from './bootstrap-owner';
import type { PlatformIntegrationChange } from './platform-config-changes';
import { integrationGroupTitleForName } from './platform-config-groups';

const log = createModuleLogger('security-alerts');

/** Local part of the address security alerts come from (`security@agents.<BASE_DOMAIN>`). */
/**
* Local part of the address security alerts come from: `security@agents.<BASE_DOMAIN>` through
* the Cloudflare binding; over SMTP every message uses `SMTP_FROM`, as the relay requires.
*/
export const SECURITY_ALERT_LOCAL_PART = 'security';

/** Account provider ids that are not a social sign-in, so linking them is not alerted. */
Expand Down Expand Up @@ -116,8 +119,8 @@ export async function deliverSecurityAlert(
now: Date = new Date()
): Promise<void> {
try {
const sender = agentEmailSenderFor(env);
if (!sender) {
const transport = await resolveSystemEmailTransport(env);
if (!transport) {
// Error, not warn: a dropped security alert is something an operator must see.
log.error('security_alert.no_sender', { kind: alert.kind });
return;
Expand All @@ -129,13 +132,10 @@ export async function deliverSecurityAlert(
log.error('security_alert.no_recipients', { kind: alert.kind });
return;
}
const from = {
email: `${SECURITY_ALERT_LOCAL_PART}@${agentEmailDomain(env.BASE_DOMAIN)}`,
name: 'SAM security',
};
const from = { email: transport.systemFrom(SECURITY_ALERT_LOCAL_PART), name: 'SAM security' };
const results = await Promise.allSettled(
recipients.map((to) =>
sender.send({ from, to, subject: email.subject, text: email.text, headers: {} })
transport.sender.send({ from, to, subject: email.subject, text: email.text, headers: {} })
)
);
const failed = results.filter((result) => result.status === 'rejected');
Expand All @@ -149,6 +149,7 @@ export async function deliverSecurityAlert(
kind: alert.kind,
recipients: recipients.length,
failed: failed.length,
transport: transport.kind,
});
} catch (error) {
log.error('security_alert.failed', { kind: alert.kind, error: errorText(error) });
Expand Down
44 changes: 44 additions & 0 deletions apps/api/tests/integration/gitlab-sign-in-trust.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
__resetPlatformConfigCacheForTest,
completeSetupWithConfig,
} from '../../src/services/platform-config';
import { startFakeSmtpServer } from '../helpers/fake-smtp-server';
import {
buildAuthApp,
type CookieJar,
Expand Down Expand Up @@ -206,6 +207,20 @@ describe('GitLab sign-in trust by identity host (vertical slice)', () => {
image: string;
};

// Box round R17 (D4): better-auth prepended its default read_user to SAM's list.
it('asks GitLab for each scope exactly once', async () => {
const env = await runtimeGitLabEnv('https://gitlab.com');
const authorizeUrl = await startSocialSignIn(app, env, jar, {
apiOrigin: API_ORIGIN,
appOrigin: APP_ORIGIN,
provider: 'gitlab',
callbackURL: CALLBACK_URL,
});
expect(authorizeUrl.searchParams.get('scope')).toBe(
'read_user api read_repository write_repository'
);
});

it('refuses a runtime self-managed host that claims the owner’s verified email (2026-11-12)', async () => {
const env = await runtimeGitLabEnv(SELF_MANAGED_HOST);
const gitlab = createFakeGitLab(SELF_MANAGED_HOST, profileClaiming(OWNER.email));
Expand Down Expand Up @@ -346,6 +361,35 @@ describe('GitLab sign-in trust by identity host (vertical slice)', () => {
expect(gitlabAccounts()).toEqual([{ account_id: '424242', user_id: OWNER.id }]);
});

// Box round R17 (D1): on a self-hosted box (SMTP, no AGENT_EMAIL) the owner alert for a newly
// linked sign-in was dropped with security_alert.no_sender. Entered through better-auth's own
// account.create.after hook, during a real GitLab callback.
it('emails the owners over SMTP when a GitLab sign-in is linked to the superadmin', async () => {
const smtp = await startFakeSmtpServer({ mode: 'plain' });
try {
const env = await runtimeGitLabEnv(PUBLIC_HOST, {
SMTP_HOST: '127.0.0.1',
SMTP_PORT: String(smtp.port),
SMTP_TLS: 'none',
SMTP_FROM: 'alerts@example.com',
} as Partial<Env>);
vi.stubGlobal('fetch', createFakeGitLab(PUBLIC_HOST, profileClaiming(OWNER.email)).fetch);
const linkedSubject =
'Subject: SAM security alert: a GitLab sign-in was linked to a superadmin account';
const linkAlerts = () => smtp.messages.filter((m) => m.data.includes(linkedSubject));
expect(linkAlerts()).toHaveLength(0);

const callback = await signInWithGitLab(env, PUBLIC_HOST);

expect(callback.headers.get('location')).toBe(CALLBACK_URL);
expect(gitlabAccounts()).toEqual([{ account_id: '424242', user_id: OWNER.id }]);
await vi.waitFor(() => expect(linkAlerts()).toHaveLength(1));
expect(linkAlerts()[0]).toMatchObject({ from: 'alerts@example.com', to: [OWNER.email] });
} finally {
await smtp.close();
}
});

it('links a self-managed host the deployer pinned in the Worker environment', async () => {
const env = baseEnv({
GITLAB_HOST: SELF_MANAGED_HOST,
Expand Down
Loading
Loading