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
5 changes: 5 additions & 0 deletions .changeset/preserve-linked-social-identities.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@logto/core': patch
---

preserve explicitly linked social accounts and their stored tokens during verified-email sign-in with another account from the same provider
74 changes: 74 additions & 0 deletions .github/workflows/fork-image.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
name: Fork image

on:
pull_request:
branches: [agentconnect-1.45]
push:
branches: ['**']
workflow_dispatch:

permissions:
contents: read

concurrency:
group: fork-image-${{ github.event_name }}-${{ github.ref }}
cancel-in-progress: true

jobs:
verify:
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
with:
buildkitd-config-inline: |
[worker.oci]
max-parallelism = 2
- name: Build verification image from source
uses: docker/build-push-action@v6
with:
context: .
target: verification
load: true
tags: logto-fork:verification
cache-from: type=gha,scope=logto-fork
cache-to: type=gha,mode=max,scope=logto-fork
- name: Verify linked identities and stored tokens
run: bash .scripts/fork/verify.sh logto-fork:verification

publish:
if: github.event_name != 'pull_request'
needs: verify
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
with:
buildkitd-config-inline: |
[worker.oci]
max-parallelism = 2
- uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Publish verified source revision
uses: docker/build-push-action@v6
with:
context: .
target: app
push: true
tags: ghcr.io/${{ github.repository }}:sha-${{ github.sha }}
labels: |
org.opencontainers.image.source=https://github.com/${{ github.repository }}
org.opencontainers.image.revision=${{ github.sha }}
org.opencontainers.image.version=1.45.0-fork
org.opencontainers.image.licenses=MPL-2.0
cache-from: type=gha,scope=logto-fork
cache-to: type=gha,mode=max,scope=logto-fork
16 changes: 16 additions & 0 deletions .scripts/fork/verification-entry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export { createUserQueries } from './queries/user.js';
export { default as SecretQueries } from './queries/secret.js';
export { createSocialLibrary } from './libraries/social.js';
export { SocialVerification } from './routes/experience/classes/verifications/social-verification.js';
export { identifyUserByVerificationRecord } from './routes/experience/classes/helpers.js';
export { toUserSocialIdentityData } from './routes/experience/classes/utils.js';
export { default as createPool } from './env-set/create-pool.js';
export { sql } from '@silverhand/slonik';
export {
Users,
Secrets,
SecretSocialConnectorRelations,
VerificationType,
SecretType,
} from '@logto/schemas';
export { ConnectorType } from '@logto/connector-kit';
210 changes: 210 additions & 0 deletions .scripts/fork/verify.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
import assert from 'node:assert/strict';
import { setTimeout as delay } from 'node:timers/promises';
import {
createPool,
createUserQueries,
SecretQueries,
createSocialLibrary,
SocialVerification,
identifyUserByVerificationRecord,
toUserSocialIdentityData,
sql,
VerificationType,
ConnectorType,
} from '/etc/logto/packages/core/verification/identity-preservation-verification.js';

// Run only against a disposable database seeded by this exact fork image.
assert(
process.env.DB_URL?.includes('logto-fork-db'),
'A disposable logto-fork-db host is required'
);
const pool = await createPool(process.env.DB_URL, false, 3, 5000, 10000);
const users = createUserQueries(pool);
const secrets = new SecretQueries(pool);
const queries = { users, secrets };
const socials = createSocialLibrary(queries, {
getLogtoConnectorById: async (id) => ({
type: ConnectorType.Social,
metadata: { target: id },
dbEntry: { syncProfile: true },
}),
});
const work = { id: 'google-work', email: 'alice@work.example.test', name: 'Work account' };
const personal = { id: 'google-personal', email: 'alice@example.test', name: 'Personal account' };
const identity = (info) => ({ userId: info.id, details: info });
const readUser = () => users.findUserById('verify-main');
const readToken = () => secrets.findSocialTokenSetSecretByUserIdAndTarget('verify-main', 'google');
const encrypted = (marker) => ({
encryptedTokenSetBase64: Buffer.from(
JSON.stringify(
Object.fromEntries(
['encryptedDek', 'iv', 'authTag', 'ciphertext'].map((key) => [
key,
Buffer.from(marker).toString('base64'),
])
)
)
).toString('base64'),
metadata: { scope: 'openid profile email', hasRefreshToken: true },
});
const token = (info, marker, target = 'google') => ({
encryptedTokenSet: encrypted(marker),
socialConnectorRelationPayload: { connectorId: target, target, identityId: info.id },
});
const saveToken = (info, marker) =>
socials.upsertSocialTokenSetSecret('verify-main', token(info, marker));

async function identify(info, { target = 'google', autoLink = true } = {}) {
const record = new SocialVerification({ socials }, queries, {
id: 'verified-record',
type: VerificationType.Social,
connectorId: target,
socialUserInfo: info,
encryptedTokenSet: encrypted(`token-${info.id}`),
});
try {
return await identifyUserByVerificationRecord(record, false);
} catch (error) {
if (!autoLink || error.code !== 'user.identity_not_exist' || !error.data?.relatedUser)
throw error;
return identifyUserByVerificationRecord(record, true);
}
}

async function login(info, options) {
const { user, syncedProfile = {} } = await identify(info, options);
const { socialIdentity, socialConnectorTokenSetSecret, ...profile } = syncedProfile;
const updated = await users.updateUserFromSignIn(user.id, {
...profile,
...(socialIdentity && { identities: toUserSocialIdentityData(socialIdentity) }),
lastSignInAt: Date.now(),
});
if (socialConnectorTokenSetSecret)
await socials.upsertSocialTokenSetSecret(user.id, socialConnectorTokenSetSecret);
return updated;
}

async function raceWithLink(change, delayed) {
let release;
let locked;
const ready = new Promise((resolve) => {
locked = resolve;
});
const gate = new Promise((resolve) => {
release = resolve;
});
const link = pool.transaction(async (connection) => {
await change(connection);
locked();
await gate;
});
await ready;
const pending = delayed().then(
(value) => ({ value }),
(error) => ({ error })
);
try {
const deadline = Date.now() + 5000;
while (true) {
const { waiting } = await pool.one(sql`
select exists(select 1 from pg_stat_activity
where datname=current_database() and wait_event_type='Lock') as waiting
`);
if (waiting) break;
assert(Date.now() < deadline, 'Delayed writer never waited for the user row lock');
await delay(20);
}
} finally {
release();
await link;
}
return pending;
}

try {
await users.insertUser({
id: 'verify-main',
primaryEmail: personal.email,
identities: { google: identity(work), github: { userId: 'github-main' } },
});
for (const target of ['google', 'gitlab']) {
await pool.query(sql`insert into connectors(id, connector_id) values (${target}, ${target})`);
}
await saveToken(work, 'work-token-before-login');
const before = await readToken();
const bound = (await readUser()).identities;
for (let i = 0; i < 2; i++) assert.equal((await login(personal)).id, 'verify-main');
assert.deepEqual((await readUser()).identities, bound);
assert.deepEqual(await readToken(), before);
assert.equal((await login(work)).id, 'verify-main');
assert.equal((await readToken()).identityId, work.id);
assert.notEqual((await readToken()).id, before.id);
console.log(
'PASS: both verified Google accounts sign in to the same user; alternate login preserves binding and token bytes; bound login refreshes its own token'
);

const afterWork = await readToken();
await assert.rejects(saveToken(personal, 'wrong-account-token'), {
code: 'user.identity_not_exists_in_current_user',
});
assert.deepEqual(await readToken(), afterWork);
await assert.rejects(identify(personal, { autoLink: false }), {
code: 'user.identity_not_exist',
});
await assert.rejects(identify({ id: 'unknown', email: 'unknown@example.test' }), {
code: 'user.identity_not_exist',
});
await users.insertUser({
id: 'verify-other',
primaryEmail: 'other@example.test',
identities: { google: { userId: 'google-other' } },
});
assert.equal((await login({ id: 'google-other', email: personal.email })).id, 'verify-other');
await login({ id: 'gitlab-main', email: personal.email }, { target: 'gitlab' });
assert.equal((await readUser()).identities.gitlab.userId, 'gitlab-main');
assert.equal((await readUser()).identities.github.userId, 'github-main');
console.log(
'PASS: unrelated email and disabled auto-link reject; exact identity owner wins; first provider link still works'
);

const replacement = { id: 'google-new-work', email: 'alice@new-work.example.test' };
const concurrentSignIn = await raceWithLink(
(connection) =>
createUserQueries(connection).updateUserById('verify-main', {
identities: { google: identity(replacement) },
}),
() => users.updateUserFromSignIn('verify-main', { identities: { google: identity(personal) } })
);
assert.ifError(concurrentSignIn.error);
assert.equal((await readUser()).identities.google.userId, replacement.id);
assert.equal((await readUser()).identities.gitlab.userId, 'gitlab-main');
await users.updateUserById('verify-main', { identities: { google: identity(work) } });
await saveToken(work, 'before-concurrent-link');
const concurrentToken = await raceWithLink(
async (connection) => {
await createUserQueries(connection).updateUserById('verify-main', {
identities: { google: identity(replacement) },
});
await createSocialLibrary(
{ users, secrets: new SecretQueries(connection) },
{}
).upsertSocialTokenSetSecret('verify-main', token(replacement, 'new-work-token'));
},
() => saveToken(work, 'stale-work-token')
);
assert.equal(concurrentToken.error?.code, 'user.identity_not_exists_in_current_user');
assert.equal((await readToken()).identityId, replacement.id);
assert.equal((await readToken()).ciphertext.toString(), 'new-work-token');
const afterUnlink = await raceWithLink(
(connection) => createUserQueries(connection).deleteUserIdentity('verify-main', 'google'),
() => saveToken(replacement, 'late-after-unlink')
);
assert.equal(afterUnlink.error?.code, 'user.identity_not_exists_in_current_user');
assert.equal(await readToken(), null);
assert.equal((await readUser()).identities.google, undefined);
console.log(
'PASS: real concurrent Link and Unlink serialize against sign-in/token writes; stale tokens cannot overwrite or return after Unlink'
);
} finally {
await pool.end();
}
32 changes: 32 additions & 0 deletions .scripts/fork/verify.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#!/usr/bin/env bash
set -euo pipefail

image="${1:?Pass the image built with --target verification}"
network="logto-fork-verify-$$"
database="logto-fork-db-$$"
runner="logto-fork-check-$$"
cleanup() {
docker rm -f "$runner" "$database" >/dev/null 2>&1 || true
docker network rm "$network" >/dev/null 2>&1 || true
}
trap cleanup EXIT
trap 'exit 130' INT TERM

docker run --rm --name "$runner" --cpus=2 --memory=3g --entrypoint sh "$image" \
-c 'cd /etc/logto/packages/core && NODE_OPTIONS=--max-old-space-size=2048 pnpm build:test && NODE_OPTIONS="--experimental-vm-modules --max-old-space-size=2048" pnpm exec jest --runInBand build/queries/user.test.js build/routes/admin-user/social.test.js build/routes/experience/index.test.js build/routes/experience/classes/helpers.test.js build/routes/experience/classes/experience-interaction.test.js build/routes/experience/classes/experience-interaction.adaptive-mfa.test.js build/routes/experience/classes/experience-interaction.trusted-device.test.js'
docker network create "$network" >/dev/null
docker run -d --name "$database" --network "$network" --cpus=1 --memory=512m \
-e POSTGRES_USER=logto -e POSTGRES_PASSWORD=local-test-only -e POSTGRES_DB=logto \
postgres:16-alpine >/dev/null
for attempt in {1..30}; do
if docker exec "$database" pg_isready -U logto >/dev/null 2>&1; then break; fi
sleep 1
done
docker exec "$database" pg_isready -U logto
docker run --rm --name "$runner" --network "$network" --cpus=1 --memory=1g \
-e "DB_URL=postgres://logto:local-test-only@${database}:5432/logto" \
--entrypoint npm "$image" run cli -- db seed --swe
docker exec "$database" psql -U logto -d logto -v ON_ERROR_STOP=1 \
-c "alter role logto_tenant_logto_default login password 'local-test-only'"
docker run --rm --name "$runner" --network "$network" --cpus=2 --memory=1g \
-e "DB_URL=postgres://logto_tenant_logto_default:local-test-only@${database}:5432/logto" "$image"
15 changes: 13 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
FROM node:22-alpine AS builder
WORKDIR /etc/logto
ENV CI=true
ENV GOMAXPROCS=2
ENV NODE_OPTIONS=--max-old-space-size=4096

# No need for Docker build
ENV PUPPETEER_SKIP_DOWNLOAD=true
Expand All @@ -29,13 +31,22 @@ ENV APPLICATIONINSIGHTS_CONNECTION_STRING=${applicationinsights_connection_strin
ARG logto_oss_survey_endpoint=
ENV LOGTO_OSS_SURVEY_ENDPOINT=${logto_oss_survey_endpoint}

RUN pnpm -r build
RUN pnpm -r --workspace-concurrency=1 build

### Add official connectors ###
ARG additional_connector_args
ENV ADDITIONAL_CONNECTOR_ARGS=${additional_connector_args}
RUN pnpm cli connector link $ADDITIONAL_CONNECTOR_ARGS -p .

###### [STAGE] Verify fork behavior ######
FROM builder AS verification
COPY .scripts/fork/verification-entry.ts /etc/logto/packages/core/src/identity-preservation-verification.ts
WORKDIR /etc/logto/packages/core
RUN pnpm exec tsup src/identity-preservation-verification.ts --out-dir verification --onSuccess true
WORKDIR /etc/logto
ENTRYPOINT ["node", "/etc/logto/.scripts/fork/verify.mjs"]

FROM builder AS production
### Prune dependencies for production ###
# Keep prune + production install in one layer to avoid extra transient disk usage.
RUN --mount=type=cache,id=pnpm-store,target=/root/.local/share/pnpm/store \
Expand All @@ -52,7 +63,7 @@ ARG private_key_rotation_grace_period=0
# Default to empty so external survey relaying stays opt-in for controlled builds/environments.
ENV LOGTO_OSS_SURVEY_ENDPOINT=${logto_oss_survey_endpoint}
ENV PRIVATE_KEY_ROTATION_GRACE_PERIOD=${private_key_rotation_grace_period}
COPY --from=builder /etc/logto .
COPY --from=production /etc/logto .
RUN mkdir -p /etc/logto/packages/cli/alteration-scripts && chmod g+w /etc/logto/packages/cli/alteration-scripts
EXPOSE 3001
ENTRYPOINT ["npm", "run"]
Expand Down
Loading
Loading