Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(hog): store OAuth logins and renew them under a lock (#127818)

Rafael Audibert58a666498dba
diff --git a/hog/src/commands/api/call.ts b/hog/src/commands/api/call.ts
index d7315c67db4c..8a3c4bfdc83e 100644
--- a/hog/src/commands/api/call.ts
+++ b/hog/src/commands/api/call.ts
@@ -1,6 +1,6 @@
import { defineCommand } from '@/core/command'
import { EXIT_USAGE, HogError } from '@/core/errors'
-import { apiConnection, findTool, grantedScopes, missingScopesError, toHogError } from '@/posthog/api-tools'
+import { findTool, grantedScopes, missingScopesError, toHogError, withApiConnection } from '@/posthog/api-tools'
function parseInput(text: string | undefined): Record<string, unknown> {
if (text === undefined) {
@@ -74,8 +74,9 @@ export default defineCommand({
)
}
- const connection = await apiConnection(ctx, options)
- const result = await library.call(tool.name, validation.input, connection, options.confirm === true)
+ const result = await withApiConnection(ctx, options, tool.readOnly || tool.idempotent, (connection) =>
+ library.call(tool.name, validation.input, connection, options.confirm === true)
+ )
await library.flush()
if (result.ok) {
return result.value
diff --git a/hog/src/commands/auth/logout.ts b/hog/src/commands/auth/logout.ts
index f13712bde2fa..f5e361fa6f8c 100644
--- a/hog/src/commands/auth/logout.ts
+++ b/hog/src/commands/auth/logout.ts
@@ -9,6 +9,9 @@ import { readSettings } from '@/posthog/settings'
interface LogoutResult {
status: 'logged_out' | 'not_logged_in'
host: string | null
+ // Whether PostHog revoked the OAuth login. Null for a personal API key, which hog can't revoke.
+ revoked: boolean | null
+ // Where to delete a personal API key, which keeps working after logout.
revokeUrl: string | null
// Why hog couldn't remove the keychain item a file login left behind. Null when there was none.
keychainLeftover: string | null
@@ -34,7 +37,7 @@ export default defineCommand({
const hosts = await logoutAll(runtime)
await clearPending(runtime, LOGIN_COMMAND)
const status = hosts.length > 0 ? 'logged_out' : 'not_logged_in'
- return { status, host: null, revokeUrl: null, keychainLeftover: null, hosts, stillSet }
+ return { status, host: null, revoked: null, revokeUrl: null, keychainLeftover: null, hosts, stillSet }
}
const settings = await readSettings(runtime)
// The same host order commands use, so logout removes the login they would send. A broken
@@ -46,6 +49,7 @@ export default defineCommand({
return {
status: outcome ? 'logged_out' : 'not_logged_in',
host: host ?? null,
+ revoked: outcome?.revoked ?? null,
revokeUrl: outcome?.revokeUrl ?? null,
keychainLeftover: outcome?.keychainLeftover ?? null,
hosts: null,
@@ -58,8 +62,16 @@ export default defineCommand({
if (loggedOut.length === 0) {
out.line('hog had no stored key to remove.')
}
- for (const { host, revokeUrl, keychainLeftover } of loggedOut) {
+ for (const { host, revoked, revokeUrl, keychainLeftover } of loggedOut) {
out.line(`${out.style('Logged out', 'green', 'bold')} of ${escapeControls(host ?? '')}.`)
+ if (revoked === false) {
+ out.line(
+ out.style(
+ "hog couldn't reach PostHog to revoke the login, so it keeps working in PostHog. Revoke it under Settings > Connected applications.",
+ 'yellow'
+ )
+ )
+ }
if (keychainLeftover) {
out.line(
out.style(
diff --git a/hog/src/commands/endpoints/endpoints.test.ts b/hog/src/commands/endpoints/endpoints.test.ts
index e24a49a5f3a4..248ad58e4a62 100644
--- a/hog/src/commands/endpoints/endpoints.test.ts
+++ b/hog/src/commands/endpoints/endpoints.test.ts
@@ -75,13 +75,20 @@ variables:
`
describe('hog endpoints', () => {
- test('list follows pages until PostHog has no more', async () => {
+ test.each([
+ ['', BASE],
+ ['under a path', 'https://ph.example.com/posthog/api/environments/7/'],
+ ])('list follows pages until PostHog has no more, for a host %s', async (_name, base) => {
const result = await runHog(['endpoints', 'list'], {
- env: AGENT,
- respond: (url) =>
- url === `${BASE}endpoints/`
- ? { status: 200, body: { results: [TRENDS], next: `${BASE}endpoints/?offset=1` } }
- : { status: 200, body: { results: [HOGQL], next: null } },
+ env: { ...AGENT, HOG_HOST: new URL('../../../', base).toString() },
+ respond: (url) => {
+ if (url === `${base}endpoints/`) {
+ return { status: 200, body: { results: [TRENDS], next: `${base}endpoints/?offset=1` } }
+ }
+ return url === `${base}endpoints/?offset=1`
+ ? { status: 200, body: { results: [HOGQL], next: null } }
+ : { status: 404, body: {} }
+ },
})
expect(
result.stdout
@@ -91,6 +98,19 @@ describe('hog endpoints', () => {
).toEqual(['weekly', 'by-type'])
})
+ test('list refuses a pagination link to another host, so the token stays on the host', async () => {
+ const result = await runHog(['endpoints', 'list'], {
+ env: AGENT,
+ respond: () => ({
+ status: 200,
+ body: { results: [TRENDS], next: 'https://ph.example.com//attacker.example/endpoints/' },
+ }),
+ })
+
+ expect(result.error()).toMatchObject({ code: 'unexpected_response' })
+ expect(result.requests.map((request) => new URL(request.url).host)).toEqual(['ph.example.com'])
+ })
+
test('pull writes short files with the project variable types, and updates a file in place', async () => {
const result = await runHog(['endpoints', 'pull', '--all', '--yes'], {
env: AGENT,
diff --git a/hog/src/commands/error-tracking/download.ts b/hog/src/commands/error-tracking/download.ts
index 8a91e2da4379..bd7451151aba 100644
--- a/hog/src/commands/error-tracking/download.ts
+++ b/hog/src/commands/error-tracking/download.ts
@@ -33,7 +33,7 @@ export default defineCommand({
],
async run({ args, options, ctx }) {
- const client = new SymbolSetClient(ctx.runtime, (await ctx.credentials()).key)
+ const client = new SymbolSetClient(ctx.runtime, await ctx.session())
const byId = !options.ref && isSymbolSetId(args.symbolSet)
const id = byId ? args.symbolSet : await resolveRef(client, args.symbolSet)
const data = await downloadSymbolSet(client, id, ctx.runtime.fetch)
diff --git a/hog/src/commands/error-tracking/release.ts b/hog/src/commands/error-tracking/release.ts
index 4f4535988795..8a4b13718cc1 100644
--- a/hog/src/commands/error-tracking/release.ts
+++ b/hog/src/commands/error-tracking/release.ts
@@ -45,7 +45,7 @@ export default defineCommand({
if (!resolved) {
return null
}
- const client = new SymbolSetClient(ctx.runtime, (await ctx.credentials()).key)
+ const client = new SymbolSetClient(ctx.runtime, await ctx.session())
if (options.dryRun) {
const existing = await findRelease(client, resolved.name, resolved.version)
const { id, hash_id, version, project } = existing ?? {
diff --git a/hog/src/core/context.ts b/hog/src/core/context.ts
index ae17fef99c10..deb4cdc0794b 100644
--- a/hog/src/core/context.ts
+++ b/hog/src/core/context.ts
@@ -2,6 +2,7 @@ import type { ApiToolLibrary } from '@posthog/mcp/src/cli/library-types'
import { PostHogApi } from '@/posthog/api'
import { resolveCredentials, type Credentials } from '@/posthog/credentials'
+import { KeySession } from '@/posthog/key-session'
import type { Mode } from './agent'
import type { CommandTree } from './command'
@@ -16,6 +17,7 @@ import { Telemetry } from './telemetry'
export class Context {
private api?: PostHogApi
private credentialsRequest?: Promise<Credentials>
+ private keySession?: Promise<KeySession>
private loaded?: Promise<LoadedConfig | undefined>
private tools?: Promise<ApiToolLibrary>
@@ -40,7 +42,7 @@ export class Context {
// The PostHog API client. Credentials resolve on first use, so commands that never call
// the API work without them.
async posthog(): Promise<PostHogApi> {
- this.api ??= new PostHogApi((await this.credentials()).key, this.runtime.fetch)
+ this.api ??= new PostHogApi(await this.session(), this.runtime.fetch)
return this.api
}
@@ -64,6 +66,19 @@ export class Context {
return this.credentialsRequest
}
+ // The key every client of this command sends, so they share its renewals.
+ session(): Promise<KeySession> {
+ this.keySession ??= this.credentials().then(
+ (credentials) =>
+ new KeySession(
+ this.runtime,
+ credentials.key,
+ credentials.source === 'store' ? credentials.storage : null
+ )
+ )
+ return this.keySession
+ }
+
// The credentials the command already asked for, so telemetry doesn't read the keychain a second time.
get requestedCredentials(): Promise<Credentials> | undefined {
return this.credentialsRequest
diff --git a/hog/src/core/file-lock.test.ts b/hog/src/core/file-lock.test.ts
new file mode 100644
index 000000000000..7723dd82f7fa
--- /dev/null
+++ b/hog/src/core/file-lock.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, test } from 'bun:test'
+
+import { fakeRuntime } from '@/testing'
+
+import { withFileLock } from './file-lock'
+
+describe('withFileLock', () => {
+ test('a process that holds the lock past the stale limit keeps it while it works', async () => {
+ const runtime = fakeRuntime()
+ const finished: string[] = []
+
+ const first = withFileLock(runtime, 'test.lock', async () => {
+ await runtime.sleep(300_000)
+ finished.push('first')
+ })
+ await runtime.sleep(1_000)
+ const second = withFileLock(runtime, 'test.lock', async () => {
+ finished.push('second')
+ })
+ await Promise.all([first, second])
+
+ expect(finished).toEqual(['first', 'second'])
+ expect(runtime.files['/home/test/.config/hog/test.lock']).toBeUndefined()
+ })
+})
diff --git a/hog/src/core/file-lock.ts b/hog/src/core/file-lock.ts
new file mode 100644
index 000000000000..08cd35cb3003
--- /dev/null
+++ b/hog/src/core/file-lock.ts
@@ -0,0 +1,91 @@
+import { randomUUID } from 'node:crypto'
+
+import { hogFile } from './paths'
+import type { Runtime } from './runtime'
+
+// A lock older than this belongs to a process that died before it removed it. The owner rewrites
+// its lock every LOCK_REFRESH_MS while it works, so waiting on another lock or on a keychain dialog
+// never makes a live lock look abandoned.
+const LOCK_STALE_MS = 180_000
+const LOCK_REFRESH_MS = 60_000
+const LOCK_POLL_MS = 250
+
+interface LockContents {
+ id?: string
+ createdAt?: number
+}
+
+async function readLock(runtime: Runtime, lock: string): Promise<LockContents | undefined> {
+ try {
+ return JSON.parse(await runtime.readFile(lock)) as LockContents
+ } catch {
+ return undefined
+ }
+}
+
+function lockContents(runtime: Runtime, id: string): string {
+ return JSON.stringify({ id, createdAt: runtime.now() })
+}
+
+async function lockHasId(runtime: Runtime, lock: string, id: string | undefined): Promise<boolean> {
+ return (await readLock(runtime, lock))?.id === id
+}
+
+// Removes the lock only while it still has `id`, so a lock another process took over stays.
+async function releaseLock(runtime: Runtime, lock: string, id: string | undefined): Promise<void> {
+ if (await lockHasId(runtime, lock, id)) {
+ await runtime.removeFile(lock)
+ }
+}
+
+async function acquireLock(runtime: Runtime, lock: string, id: string): Promise<void> {
+ // A lock that can't be read yet may be one another process is still writing, so its age counts
+ // from when this process first saw it.
+ let unreadableSince: number | undefined
+ while (!(await runtime.createFile(lock, lockContents(runtime, id)))) {
+ const contents = await readLock(runtime, lock)
+ if (contents?.createdAt !== undefined) {
+ unreadableSince = undefined
+ }
+ const createdAt = contents?.createdAt ?? (unreadableSince ??= runtime.now())
+ if (runtime.now() - createdAt <= LOCK_STALE_MS) {
+ await runtime.sleep(LOCK_POLL_MS)
+ continue
+ }
+ // Another process may have taken the stale lock over since the read above. Removing only
+ // the lock this process judged stale keeps it from removing that process's live lock.
+ await releaseLock(runtime, lock, contents?.id)
+ unreadableSince = undefined
+ }
+}
+
+async function keepLockFresh(runtime: Runtime, lock: string, id: string, signal: AbortSignal): Promise<void> {
+ try {
+ for (;;) {
+ await runtime.sleep(LOCK_REFRESH_MS, signal)
+ if (signal.aborted || !(await lockHasId(runtime, lock, id))) {
+ return
+ }
+ await runtime.writePrivateFile(lock, lockContents(runtime, id))
+ }
+ } catch {
+ // A failed refresh only stops the refreshing. The lock may then look abandoned after
+ // LOCK_STALE_MS, which is the behavior without refreshing, and the work keeps going.
+ }
+}
+
+// Each hog process that reaches the same lock waits for the one before it.
+export async function withFileLock<T>(runtime: Runtime, name: string, work: () => Promise<T>): Promise<T> {
+ const lock = hogFile(runtime, name)
+ const id = randomUUID()
+ await acquireLock(runtime, lock, id)
+ const done = new AbortController()
+ const refreshing = keepLockFresh(runtime, lock, id, done.signal)
+ try {
+ return await work()
+ } finally {
+ done.abort()
+ await refreshing
+ await releaseLock(runtime, lock, id)
+ }
+}
diff --git a/hog/src/core/runtime.ts b/hog/src/core/runtime.ts
index c7ee6b643878..d2481d6c8c8d 100644
--- a/hog/src/core/runtime.ts
+++ b/hog/src/core/runtime.ts
@@ -58,6 +58,8 @@ export interface Runtime {
// Writes a project file, such as a generated SDK, and creates the folders above it.
writeFile: (path: string, contents: string) => Promise<void>
writePrivateFile: (path: string, contents: string) => Promise<void>
+ // Creates a private file unless the path exists, and resolves to false if it does, so it works as a lock.
+ createFile: (path: string, contents: string) => Promise<boolean>
removeFile: (path: string) => Promise<void>
readStdin: () => Promise<string>
// Resolves to false when no browser could be started, for example on a server without one.
@@ -109,7 +111,13 @@ async function tracked<T>(call: () => Promise<T>): Promise<T> {
function bunSecrets(service: string): Secrets {
return {
get: (name) => tracked(() => Bun.secrets.get({ service, name })),
- set: (name, value) => tracked(() => Bun.secrets.set({ service, name, value })),
+ // Windows only: the default `enterprise` lets a roaming profile copy the item to every machine the
+ // person signs in to. Bun before 1.4.3 ignores the option, so the item still roams there.
+ // TODO: require Bun 1.4.3+ (engines.bun and the flox pin) once hog can move to it.
+ set: (name, value) =>
+ tracked(() =>
+ Bun.secrets.set({ service, name, value, persist: 'local' } as Parameters<typeof Bun.secrets.set>[0])
+ ),
delete: (name) => tracked(() => Bun.secrets.delete({ service, name })),
}
}
@@ -202,6 +210,18 @@ export function processRuntime(): Runtime {
throw error
}
},
+ createFile: async (path, contents) => {
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 })
+ try {
+ await writeFile(path, contents, { mode: 0o600, flag: 'wx' })
+ return true
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') {
+ return false
+ }
+ throw error
+ }
+ },
removeFile: (path) => rm(path, { force: true }),
readStdin: () => new Response(Bun.stdin.stream()).text(),
openUrl: async (url) => {
diff --git a/hog/src/core/telemetry.test.ts b/hog/src/core/telemetry.test.ts
index 2434a731b248..467aa0ff78a8 100644
--- a/hog/src/core/telemetry.test.ts
+++ b/hog/src/core/telemetry.test.ts
@@ -63,6 +63,7 @@ describe('telemetry', () => {
['with no identity cache', {}],
// A broken cache must not fail the command.
['with a cache that is not an object', { '/home/test/.posthog/hog-telemetry-identity.json': 'null' }],
+ ['with a broken cache entry', { '/home/test/.posthog/hog-telemetry-identity.json': '{"other": null}' }],
])(
'a PostHog Cloud key ties events to its user and groups, and hog looks them up once, %s',
async (_name, files) => {
diff --git a/hog/src/core/telemetry.ts b/hog/src/core/telemetry.ts
index b640543e8180..339e7105d27c 100644
--- a/hog/src/core/telemetry.ts
+++ b/hog/src/core/telemetry.ts
@@ -216,13 +216,17 @@ export class Telemetry {
} catch {
return undefined
}
- const cacheKey = createHash('sha256').update(`${key.host}\n${key.projectId}\n${key.token}`).digest('hex')
+ const cacheKey = createHash('sha256').update(`${key.host}\n${key.projectId}\n${key.loginKey}`).digest('hex')
let cache: Record<string, CachedIdentity> = {}
try {
const parsed: unknown = JSON.parse(await this.runtime.readFile(path))
// A cache that isn't an object is broken, so hog starts a new one instead of failing the command.
if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
- cache = parsed as Record<string, CachedIdentity>
+ cache = Object.fromEntries(
+ Object.entries(parsed).filter(
+ ([, entry]) => typeof (entry as Partial<CachedIdentity> | null)?.checkedAt === 'number'
+ )
+ ) as Record<string, CachedIdentity>
}
} catch {
// No cache yet.
@@ -233,6 +237,8 @@ export class Telemetry {
return cached
}
const identity = await this.lookup(key)
+ // Entries old enough to be looked up again anyway are dropped, so logins that ended don't pile up.
+ cache = Object.fromEntries(Object.entries(cache).filter(([, entry]) => now - entry.checkedAt < 30 * DAY_MS))
cache[cacheKey] = { ...identity, checkedAt: now }
try {
await this.runtime.writePrivateFile(path, JSON.stringify(cache))
diff --git a/hog/src/error-tracking/run.ts b/hog/src/error-tracking/run.ts
index 4c3cb7013364..48ca6d714b81 100644
--- a/hog/src/error-tracking/run.ts
+++ b/hog/src/error-tracking/run.ts
@@ -152,10 +152,10 @@ export class Session {
getClient(): Promise<SymbolSetClient> {
this.client ??= this.ctx
- .credentials()
+ .session()
.then(
- ({ key }) =>
- new SymbolSetClient(this.ctx.runtime, key, () =>
+ (session) =>
+ new SymbolSetClient(this.ctx.runtime, session, () =>
this.ctx.telemetry.capture('error_tracking_cli_sourcemaps_upload_endpoint_fallback')
)
)
diff --git a/hog/src/error-tracking/upload.ts b/hog/src/error-tracking/upload.ts
index 13eae74b69b5..a7b6f6c0effa 100644
--- a/hog/src/error-tracking/upload.ts
+++ b/hog/src/error-tracking/upload.ts
@@ -1,7 +1,8 @@
import { HogError } from '@/core/errors'
import type { Runtime } from '@/core/runtime'
-import type { AccessKey } from '@/posthog/access-key'
import { USER_AGENT } from '@/posthog/api'
+import { hostUrl } from '@/posthog/host'
+import type { KeySession } from '@/posthog/key-session'
import { contentHash } from './container'
@@ -145,35 +146,40 @@ export class SymbolSetClient {
constructor(
private readonly runtime: Runtime,
- private readonly key: AccessKey,
+ private readonly session: KeySession,
private readonly onFallback: () => void = () => {}
) {
this.throttle = new Throttle(runtime, RATE_LIMIT_PER_MINUTE)
}
- // Project-scoped API URL, resolved the way posthog-cli's `Url::join` does.
+ // Project-scoped API URL. hostUrl keeps the path a self-hosted PostHog sits under, which
+ // posthog-cli's `Url::join` drops, and gives the same URL for a host without one.
projectUrl(path: string): URL {
- return new URL(path, new URL(`api/projects/${this.key.projectId}/`, this.key.host))
+ const { projectId, host } = this.session.current
+ return new URL(path, hostUrl(host, `api/projects/${projectId}/`))
}
async api(method: 'GET' | 'POST', path: string, body?: unknown): Promise<unknown> {
await this.throttle.wait()
const url = this.projectUrl(path)
- let response: Response
- try {
- response = await this.runtime.fetch(url, {
- method,
- headers: {
- Authorization: `Bearer ${this.key.token}`,
- 'Content-Type': 'application/json',
- 'User-Agent': USER_AGENT,
- },
- body: body === undefined ? undefined : JSON.stringify(body),
- timeoutMs: REQUEST_TIMEOUT_MS,
- })
- } catch (error) {
- throw new ApiFailure(undefined, error instanceof Error ? error.message : String(error), url.toString())
+ // Only a failed request becomes an ApiFailure. A renewal that fails keeps its own error and hint.
+ const send = async (token: string): Promise<Response> => {
+ try {
+ return await this.runtime.fetch(url, {
+ method,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ 'User-Agent': USER_AGENT,
+ },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ timeoutMs: REQUEST_TIMEOUT_MS,
+ })
+ } catch (error) {
+ throw new ApiFailure(undefined, error instanceof Error ? error.message : String(error), url.toString())
+ }
}
+ const response = await this.session.send(send, (answer) => answer.status === 401)
const text = await response.text()
if (!response.ok) {
throw new ApiFailure(response.status, text, url.toString())
diff --git a/hog/src/posthog/access-key.ts b/hog/src/posthog/access-key.ts
index 151f4292342e..884e80253357 100644
--- a/hog/src/posthog/access-key.ts
+++ b/hog/src/posthog/access-key.ts
@@ -4,8 +4,18 @@ import type { StoreChoice, StoredSecret } from '@/posthog/credential-store/types
import { sendRequest } from './api'
import { hostUrl } from './host'
+import { OAuthLogin } from './oauth'
import type { LoginRecord } from './settings'
+// What `hog auth status` shows about a key.
+export interface AccessKeyStatus {
+ kind: 'personal_api_key' | 'oauth'
+ // Null for a personal API key hog hasn't asked PostHog about.
+ scopes: string[] | null
+ // Epoch milliseconds. Null for a key that doesn't expire.
+ expiresAt: number | null
+}
+
export interface LogoutOutcome {
// Whether PostHog revoked the login. Null for a key hog can't revoke.
revoked: boolean | null
@@ -26,10 +36,14 @@ export interface AccessKey {
readonly projectId: string
// What PostHog takes as the bearer token.
readonly token: string
- // A key that works for the rest of the command, renewed if it is about to expire.
- fresh(runtime: Runtime, storage: AccessKeyStorage): Promise<AccessKey>
+ // Stays the same for the whole login, unlike an OAuth token, which changes on each renewal.
+ readonly loginKey: string
+ // A key with time left, renewed if it is about to expire, or if it is still `rejectedToken`,
+ // a token PostHog refused.
+ fresh(runtime: Runtime, storage: AccessKeyStorage, rejectedToken?: string): Promise<AccessKey>
// The key as PostHog sees it, before hog stores it. Throws when PostHog rejects it.
verify(runtime: Runtime): Promise<AccessKey>
+ status(): AccessKeyStatus
logout(runtime: Runtime): Promise<LogoutOutcome>
// The credential store keeps the secret, and settings.json keeps the record.
secret(): StoredSecret
@@ -56,10 +70,18 @@ export class PersonalAPIKey implements AccessKey {
return this.apiKey
}
+ get loginKey(): string {
+ return this.apiKey
+ }
+
async fresh(): Promise<AccessKey> {
return this
}
+ status(): AccessKeyStatus {
+ return { kind: 'personal_api_key', scopes: this.scopes, expiresAt: null }
+ }
+
// A key someone deleted, or one pasted only in part, would otherwise fail only at the first
// command that uses it. A key PostHog just issued already came with its scopes, so it skips the
// check: its approval is short-lived and a slow check could lose it.
@@ -69,7 +91,7 @@ export class PersonalAPIKey implements AccessKey {
}
const response = await sendRequest(runtime.fetch, hostUrl(this.host, 'api/personal_api_keys/@current/'), {
method: 'GET',
- apiKey: this.apiKey,
+ token: this.apiKey,
timeoutMs: KEY_CHECK_TIMEOUT_MS,
})
if (response.status === 401) {
@@ -119,5 +141,9 @@ export function accessKeyFromStorage(record: LoginRecord, secret: StoredSecret):
if (record.type === 'personal_api_key' && 'apiKey' in secret) {
return new PersonalAPIKey({ host: record.host, projectId: record.projectId, apiKey: secret.apiKey })
}
+ if (record.type === 'oauth' && 'accessToken' in secret) {
+ const { host, projectId, expiresAt, scopes, loginId } = record
+ return new OAuthLogin({ host, projectId, expiresAt, scopes, loginId, ...secret })
+ }
return undefined
}
diff --git a/hog/src/posthog/api-tools.ts b/hog/src/posthog/api-tools.ts
index b0b791bb1658..b4fee2915304 100644
--- a/hog/src/posthog/api-tools.ts
+++ b/hog/src/posthog/api-tools.ts
@@ -107,11 +107,13 @@ export async function apiConnection(
throw new HogError('invalid_input', `${flag} is empty.`, `Pass an ID, or leave out ${flag}.`, EXIT_USAGE)
}
}
- const { key } = await ctx.credentials()
+ const session = await ctx.session()
+ const apiKey = await session.token()
+ const key = session.current
// The saved project can belong to another organization, so an organization override drops it.
const projectId = scope.projectId ?? (scope.organizationId ? undefined : key.projectId)
return {
- apiKey: key.token,
+ apiKey,
host: key.host,
...(projectId ? { projectId } : {}),
...(scope.organizationId ? { organizationId: scope.organizationId } : {}),
@@ -120,6 +122,24 @@ export async function apiConnection(
}
}
+// A tool can send several requests, so only a tool that is safe to run twice runs again after a 401.
+export async function withApiConnection<T>(
+ ctx: Context,
+ scope: { projectId?: string | undefined; organizationId?: string | undefined },
+ canRunTwice: boolean,
+ call: (connection: ApiConnection) => Promise<ApiToolResult<T>>
+): Promise<ApiToolResult<T>> {
+ const connection = await apiConnection(ctx, scope)
+ if (!canRunTwice) {
+ return call(connection)
+ }
+ const session = await ctx.session()
+ return session.send(
+ (apiKey) => call({ ...connection, apiKey }),
+ (result) => !result.ok && result.error.code === 'api_error' && result.error.status === 401
+ )
+}
+
export function missingScopesError(tool: string, scopes: readonly string[]): HogError {
return new HogError(
'missing_scopes',
diff --git a/hog/src/posthog/api.ts b/hog/src/posthog/api.ts
index 8bcdf1c903d0..f6a487402434 100644
--- a/hog/src/posthog/api.ts
+++ b/hog/src/posthog/api.ts
@@ -3,7 +3,8 @@ import { parseLossless } from '@/core/raw-json'
import type { RuntimeFetch } from '@/core/runtime'
import { VERSION } from '@/version'
-import type { AccessKey } from './access-key'
+import { hostUrl } from './host'
+import type { KeySession } from './key-session'
export const USER_AGENT = `hog/${VERSION}`
// Generous, because a HogQL query can run for minutes. It only stops a connection that hangs.
@@ -14,7 +15,9 @@ type Method = 'GET' | 'POST' | 'PATCH' | 'DELETE'
export interface HttpRequest {
method: Method
body?: unknown
- apiKey?: string
+ // Sent form encoded instead of `body`, as the OAuth endpoints expect.
+ form?: Record<string, string>
+ token?: string
timeoutMs?: number
}
@@ -28,9 +31,12 @@ export interface HttpResponse {
// Sends one JSON request to PostHog. Any failure before the whole body arrives, including the
// deadline, is a `network_error`, so callers handle a dropped connection in one place.
export async function sendRequest(fetchFn: RuntimeFetch, url: URL, request: HttpRequest): Promise<HttpResponse> {
- const headers: Record<string, string> = { 'Content-Type': 'application/json', 'User-Agent': USER_AGENT }
- if (request.apiKey) {
- headers.Authorization = `Bearer ${request.apiKey}`
+ const headers: Record<string, string> = {
+ 'Content-Type': request.form ? 'application/x-www-form-urlencoded' : 'application/json',
+ 'User-Agent': USER_AGENT,
+ }
+ if (request.token) {
+ headers.Authorization = `Bearer ${request.token}`
}
let response: Response
let text: string
@@ -38,7 +44,11 @@ export async function sendRequest(fetchFn: RuntimeFetch, url: URL, request: Http
response = await fetchFn(url, {
method: request.method,
headers,
- body: request.body === undefined ? undefined : JSON.stringify(request.body),
+ body: request.form
+ ? new URLSearchParams(request.form).toString()
+ : request.body === undefined
+ ? undefined
+ : JSON.stringify(request.body),
timeoutMs: request.timeoutMs ?? REQUEST_TIMEOUT_MS,
})
text = await response.text()
@@ -77,17 +87,28 @@ export class ApiError extends HogError {
export class PostHogApi {
constructor(
- private readonly key: AccessKey,
+ private readonly session: KeySession,
private readonly fetchFn: RuntimeFetch
) {}
// Paths are relative to the project, so `query` is /api/environments/<project id>/query. A path
// that starts with `/`, like `/api/users/@me/`, is relative to the host instead.
private url(path: string): URL {
- const base = path.startsWith('/')
- ? this.key.host
- : new URL(`api/environments/${this.key.projectId}/`, this.key.host)
- return new URL(path, base)
+ const { host, projectId } = this.session.current
+ // hostUrl keeps the path a self-hosted PostHog can sit under, which `new URL` would drop. A
+ // path from a pagination link already starts with it.
+ const root = hostUrl(host, '')
+ let url: URL
+ if (path.startsWith('/')) {
+ url = path.startsWith(root.pathname) ? new URL(path, root) : hostUrl(host, path.slice(1))
+ } else {
+ url = new URL(path, hostUrl(host, `api/environments/${projectId}/`))
+ }
+ // A path from a link PostHog sent, such as `//other.example/`, must not carry the token elsewhere.
+ if (url.origin !== root.origin) {
+ throw new HogError('unexpected_response', `PostHog sent a link to another host: ${url.origin}.`)
+ }
+ return url
}
get<T>(path: string): Promise<T> {
@@ -107,11 +128,11 @@ export class PostHogApi {
}
private async request<T>(method: Method, path: string, body?: unknown): Promise<T> {
- const response = await sendRequest(this.fetchFn, this.url(path), {
- method,
- body,
- apiKey: this.key.token,
- })
+ const url = this.url(path)
+ const response = await this.session.send(
+ (token) => sendRequest(this.fetchFn, url, { method, body, token }),
+ (answer) => answer.status === 401
+ )
if (response.text && response.json === undefined) {
throw new HogError(
'unexpected_response',
diff --git a/hog/src/posthog/credential-store/credential-store.test.ts b/hog/src/posthog/credential-store/credential-store.test.ts
index 5c7744e2e7c6..2c8eee8aa1b9 100644
--- a/hog/src/posthog/credential-store/credential-store.test.ts
+++ b/hog/src/posthog/credential-store/credential-store.test.ts
@@ -16,6 +16,8 @@ function secret(apiKey: string): StoredSecret {
return { apiKey }
}
+const US_OAUTH: StoredSecret = { accessToken: 'pha_access', refreshToken: 'phr_refresh' }
+
// A keychain that answers after `delayMs` of fake time, or never, or fails the way Bun reports a
// denied dialog.
function dialogSecrets(behavior: number | 'never' | 'denied'): (runtime: FakeRuntime) => Secrets {
@@ -51,16 +53,16 @@ describe('credential stores', () => {
expect(await store.remove(EU)).toBe(false)
await store.write(EU, secret('phx_first'))
- await store.write(US, secret('phx_us'))
+ await store.write(US, US_OAUTH)
await store.write(`${EU}/`, secret('phx_second'))
expect(await store.read(EU)).toEqual(secret('phx_second'))
- expect(await store.read(US)).toEqual(secret('phx_us'))
+ expect(await store.read(US)).toEqual(US_OAUTH)
expect(await store.remove(EU)).toBe(true)
expect(await store.read(EU)).toBeUndefined()
- expect(await store.read(US)).toEqual(secret('phx_us'))
+ expect(await store.read(US)).toEqual(US_OAUTH)
})
})
@@ -88,7 +90,7 @@ describe('credential stores', () => {
const start = runtime.now()
const outcome = await new KeychainStore(runtime).read(EU).then(
- (stored) => stored?.apiKey,
+ (stored) => (stored && 'apiKey' in stored ? stored.apiKey : stored),
(error: unknown) => (error instanceof HogError ? error.code : error)
)
diff --git a/hog/src/posthog/credential-store/helpers.ts b/hog/src/posthog/credential-store/helpers.ts
index 60249cc40b41..47d968d61494 100644
--- a/hog/src/posthog/credential-store/helpers.ts
+++ b/hog/src/posthog/credential-store/helpers.ts
@@ -11,5 +11,11 @@ export function parseJson(text: string): unknown {
// A stored value hog doesn't recognize, such as one a later version wrote, reads as no login.
export function parseSecret(value: unknown): StoredSecret | undefined {
const item = value as Record<string, unknown> | null
- return typeof item?.apiKey === 'string' ? { apiKey: item.apiKey } : undefined
+ if (typeof item?.apiKey === 'string') {
+ return { apiKey: item.apiKey }
+ }
+ if (typeof item?.accessToken === 'string' && typeof item.refreshToken === 'string') {
+ return { accessToken: item.accessToken, refreshToken: item.refreshToken }
+ }
+ return undefined
}
diff --git a/hog/src/posthog/credential-store/types.ts b/hog/src/posthog/credential-store/types.ts
index 4ded33dd50b3..3206c35ca5af 100644
--- a/hog/src/posthog/credential-store/types.ts
+++ b/hog/src/posthog/credential-store/types.ts
@@ -4,7 +4,12 @@ export interface PersonalAPIKeySecret {
apiKey: string
}
-export type StoredSecret = PersonalAPIKeySecret
+export interface OAuthSecret {
+ accessToken: string
+ refreshToken: string
+}
+
+export type StoredSecret = PersonalAPIKeySecret | OAuthSecret
export type StoreKind = 'keychain' | 'file' | 'memory'
diff --git a/hog/src/posthog/credentials.ts b/hog/src/posthog/credentials.ts
index 295307382fed..d6499e68d079 100644
--- a/hog/src/posthog/credentials.ts
+++ b/hog/src/posthog/credentials.ts
@@ -5,7 +5,7 @@ import type { Env, Runtime } from '@/core/runtime'
import type { StoreChoice } from '@/posthog/credential-store/types'
import { loginStorage, readLogin } from '@/posthog/login/stored'
-import { PersonalAPIKey, type AccessKey } from './access-key'
+import { PersonalAPIKey, type AccessKey, type AccessKeyStorage } from './access-key'
import { hostKey, sameHost } from './host'
import { readSettings } from './settings'
@@ -17,7 +17,7 @@ export type Credentials = { key: AccessKey } & (
| { source: 'dotenv-file'; path: string }
// What `hog auth login` or `hog auth migrate` saved. `path` is the file that holds the secret,
// and null for the keychain.
- | { source: 'store'; store: StoreChoice; path: string | null }
+ | { source: 'store'; store: StoreChoice; path: string | null; storage: AccessKeyStorage }
)
export type CredentialSource = Credentials['source']
@@ -226,9 +226,10 @@ export async function resolveCredentials(
EXIT_USAGE
)
}
- const key = await login.key.fresh(runtime, loginStorage(runtime, login))
+ const storage = loginStorage(runtime, login)
+ const key = await login.key.fresh(runtime, storage)
const { store } = login
- return { key, source: 'store', store: store.kind, path: store.path }
+ return { key, source: 'store', store: store.kind, path: store.path, storage }
}
}
diff --git a/hog/src/posthog/key-session.ts b/hog/src/posthog/key-session.ts
new file mode 100644
index 000000000000..6213b2b857ce
--- /dev/null
+++ b/hog/src/posthog/key-session.ts
@@ -0,0 +1,47 @@
+import type { Runtime } from '@/core/runtime'
+
+import type { AccessKey, AccessKeyStorage } from './access-key'
+
+// A command can outlive an OAuth access token, so each request renews it first when it is about to
+// expire, and renews it and sends once more when PostHog answers 401. PostHog checks the token
+// before it does any work, so the second send is safe for a POST too.
+export class KeySession {
+ // PostHog also answers 401 for a valid token when the account can't act. Once a renewed token
+ // gets 401 too, renewing again for every request would only rotate the login for nothing.
+ private renewalHelps = true
+
+ constructor(
+ private readonly runtime: Runtime,
+ private key: AccessKey,
+ // Null for a key from the environment or --dotenv-file, which hog can't renew.
+ private readonly storage: AccessKeyStorage | null
+ ) {}
+
+ get current(): AccessKey {
+ return this.key
+ }
+
+ async token(): Promise<string> {
+ if (this.storage) {
+ this.key = await this.key.fresh(this.runtime, this.storage)
+ }
+ return this.key.token
+ }
+
+ async send<T>(attempt: (token: string) => Promise<T>, rejected: (result: T) => boolean): Promise<T> {
+ const token = await this.token()
+ const result = await attempt(token)
+ if (!rejected(result) || !this.storage || !this.renewalHelps) {
+ return result
+ }
+ const renewed = await this.key.fresh(this.runtime, this.storage, token)
+ // A personal API key can't be renewed, so its 401 stands.
+ if (renewed.token === token) {
+ return result
+ }
+ this.key = renewed
+ const retried = await attempt(renewed.token)
+ this.renewalHelps = !rejected(retried)
+ return retried
+ }
+}
diff --git a/hog/src/posthog/login/flow.ts b/hog/src/posthog/login/flow.ts
index 88c618d72d65..f6dfb86f6f42 100644
--- a/hog/src/posthog/login/flow.ts
+++ b/hog/src/posthog/login/flow.ts
@@ -7,6 +7,7 @@ import { probeKeychain } from '@/posthog/credential-store/keychain'
import { openStore } from '@/posthog/credential-store/open'
import type { StoreChoice } from '@/posthog/credential-store/types'
import { pollDeviceLogin, startDeviceLogin, type Approval, type PendingLogin } from '@/posthog/device-auth'
+import { withLoginLock } from '@/posthog/oauth'
import { loginFor, readSettings } from '@/posthog/settings'
import { writeLogin } from './stored'
@@ -50,24 +51,28 @@ export async function saveLogin(runtime: Runtime, unverified: AccessKey): Promis
let store = openStore(runtime, probe.usable ? 'keychain' : 'file')
let keychainError = probe.usable ? null : probe.reason
const { host, projectId } = key
- try {
- // A keychain that times out sends the login to the file below.
- await writeLogin(runtime, store, key, { lastLogin: true, removeIfLate: true })
- } catch (error) {
- // The probe writes an item of its own, so the keychain can still refuse this host's item,
- // such as one an older hog build saved.
- if (store.kind !== 'keychain' || !(error instanceof HogError) || !error.code.startsWith('keychain_')) {
- throw error
+ // Under the renewal lock, so a renewal of the previous login that is still in flight can't
+ // store that login over this one.
+ await withLoginLock(runtime, host, async () => {
+ try {
+ // A keychain that times out sends the login to the file below.
+ await writeLogin(runtime, store, key, { lastLogin: true, removeIfLate: true })
+ } catch (error) {
+ // The probe writes an item of its own, so the keychain can still refuse this host's item,
+ // such as one an older hog build saved.
+ if (store.kind !== 'keychain' || !(error instanceof HogError) || !error.code.startsWith('keychain_')) {
+ throw error
+ }
+ keychainError = error.message
+ store = new FileStore(runtime)
+ // The failed keychain write can still land after hog gave up on it.
+ await writeLogin(runtime, store, key, { lastLogin: true, keychainLeftover: true })
}
- keychainError = error.message
- store = new FileStore(runtime)
- // The failed keychain write can still land after hog gave up on it.
- await writeLogin(runtime, store, key, { lastLogin: true, keychainLeftover: true })
- }
- // Only an old file login is removed. Removing a keychain login after a failed probe would wait for the keychain again.
- if (loginFor(previous, host)?.store === 'file' && store.kind === 'keychain') {
- await new FileStore(runtime).remove(host)
- }
+ // Only an old file login is removed. Removing a keychain login after a failed probe would wait for the keychain again.
+ if (loginFor(previous, host)?.store === 'file' && store.kind === 'keychain') {
+ await new FileStore(runtime).remove(host)
+ }
+ })
await clearPending(runtime, LOGIN_COMMAND)
return {
host,
diff --git a/hog/src/posthog/login/stored.test.ts b/hog/src/posthog/login/stored.test.ts
new file mode 100644
index 000000000000..39e3fefd5f7b
--- /dev/null
+++ b/hog/src/posthog/login/stored.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, test } from 'bun:test'
+
+import { PersonalAPIKey } from '@/posthog/access-key'
+import { FileStore } from '@/posthog/credential-store/file'
+import { fakeRuntime } from '@/testing'
+
+import { writeLogin } from './stored'
+
+const EU = 'https://eu.posthog.com'
+const US = 'https://us.posthog.com'
+
+function login(host: string, apiKey: string): PersonalAPIKey {
+ return new PersonalAPIKey({ host, projectId: '42', apiKey })
+}
+
+describe('writeLogin', () => {
+ test('keeps both logins when two hog processes save logins to different hosts at once', async () => {
+ const runtime = fakeRuntime()
+ const store = new FileStore(runtime)
+
+ await Promise.all([
+ writeLogin(runtime, store, login(EU, 'phx_eu')),
+ writeLogin(runtime, store, login(US, 'phx_us')),
+ ])
+
+ expect(Object.keys(JSON.parse(runtime.files[store.path] ?? '{}')).sort()).toEqual([EU, US])
+ const settings = JSON.parse(runtime.files['/home/test/.config/hog/settings.json'] ?? '{}')
+ expect(Object.keys(settings.logins).sort()).toEqual([EU, US])
+ })
+})
diff --git a/hog/src/posthog/login/stored.ts b/hog/src/posthog/login/stored.ts
index eda1662a40c1..9abefd64788a 100644
--- a/hog/src/posthog/login/stored.ts
+++ b/hog/src/posthog/login/stored.ts
@@ -1,12 +1,18 @@
import { HogError } from '@/core/errors'
+import { withFileLock } from '@/core/file-lock'
import type { Runtime } from '@/core/runtime'
import { accessKeyFromStorage, type AccessKey, type AccessKeyStorage, type LogoutOutcome } from '@/posthog/access-key'
import { FileStore } from '@/posthog/credential-store/file'
import { KeychainStore } from '@/posthog/credential-store/keychain'
import { openStore } from '@/posthog/credential-store/open'
import { hostKey, type HostKey } from '@/posthog/host'
+import { withLoginLock } from '@/posthog/oauth'
import { loginFor, readSettings, withLogin, writeSettings, type HogSettings } from '@/posthog/settings'
+// settings.json and the credentials file hold every host's login, so each write reads them, changes
+// one entry and writes them back. The lock keeps two hog processes from dropping each other's entry.
+const LOGINS_LOCK = 'logins.lock'
+
export interface LoggedOut extends LogoutOutcome {
// Why hog couldn't remove the keychain item a file login left behind. Null when there was none.
keychainLeftover: string | null
@@ -53,46 +59,57 @@ export async function writeLogin(
key: AccessKey,
options: { lastLogin?: boolean; removeIfLate?: boolean; keychainLeftover?: boolean } = {}
): Promise<void> {
- await store.write(key.host, key.secret(), { removeIfLate: options.removeIfLate })
- const current = await readSettings(runtime)
- const previous = loginFor(current, key.host)
- const record = key.record(store.kind)
- const keychainLeftover =
- store.kind === 'file' &&
- (options.keychainLeftover === true || previous?.store === 'keychain' || previous?.keychainLeftover === true)
- const settings = withLogin(current, key.host, keychainLeftover ? { ...record, keychainLeftover } : record)
- await writeSettings(runtime, options.lastLogin ? { ...settings, host: key.host } : settings)
+ await withFileLock(runtime, LOGINS_LOCK, async () => {
+ await store.write(key.host, key.secret(), { removeIfLate: options.removeIfLate })
+ const current = await readSettings(runtime)
+ const previous = loginFor(current, key.host)
+ const record = key.record(store.kind)
+ const keychainLeftover =
+ store.kind === 'file' &&
+ (options.keychainLeftover === true || previous?.store === 'keychain' || previous?.keychainLeftover === true)
+ const settings = withLogin(current, key.host, keychainLeftover ? { ...record, keychainLeftover } : record)
+ await writeSettings(runtime, options.lastLogin ? { ...settings, host: key.host } : settings)
+ })
}
// Resolves to false when the store held nothing for the host.
export async function removeLogin(runtime: Runtime, host: string, store: KeychainStore | FileStore): Promise<boolean> {
- const removed = await store.remove(host)
- const settings = withLogin(await readSettings(runtime), host, undefined)
- const lastLogin = settings.host !== undefined && hostKey(settings.host) === hostKey(host)
- await writeSettings(runtime, lastLogin ? { logins: settings.logins } : settings)
- return removed
+ return withFileLock(runtime, LOGINS_LOCK, async () => {
+ const removed = await store.remove(host)
+ const settings = withLogin(await readSettings(runtime), host, undefined)
+ const lastLogin = settings.host !== undefined && hostKey(settings.host) === hostKey(host)
+ await writeSettings(runtime, lastLogin ? { logins: settings.logins } : settings)
+ return removed
+ })
}
// Logs this machine out of `host`: the key revokes itself where it can, and hog removes its
// stored copy. Resolves to undefined when hog had no login to remove.
+// Under the renewal lock, so a renewal in another hog process can neither restore the login after
+// this removes it, nor rotate the refresh token this revokes.
export async function logout(runtime: Runtime, host: string): Promise<LoggedOut | undefined> {
- const settings = await readSettings(runtime)
- const record = loginFor(settings, host)
- const login = await readLogin(runtime, settings, host)
- if (!login) {
- // The file entry can be gone while the record still names a keychain item left behind.
- if (!record?.keychainLeftover) {
+ return withLoginLock(runtime, host, async () => {
+ const settings = await readSettings(runtime)
+ const record = loginFor(settings, host)
+ const login = await readLogin(runtime, settings, host)
+ if (!login) {
+ // The file entry can be gone while the record still names a keychain item left behind.
+ if (!record?.keychainLeftover) {
+ return undefined
+ }
+ await removeLogin(runtime, host, openStore(runtime, record.store))
+ return { revoked: null, revokeUrl: null, keychainLeftover: await removeKeychainLeftover(runtime, host) }
+ }
+ const [outcome, removed] = await Promise.all([
+ login.key.logout(runtime),
+ removeLogin(runtime, host, login.store),
+ ])
+ if (!removed) {
return undefined
}
- await removeLogin(runtime, host, openStore(runtime, record.store))
- return { revoked: null, revokeUrl: null, keychainLeftover: await removeKeychainLeftover(runtime, host) }
- }
- const [outcome, removed] = await Promise.all([login.key.logout(runtime), removeLogin(runtime, host, login.store)])
- if (!removed) {
- return undefined
- }
- const leftover = record?.keychainLeftover ? await removeKeychainLeftover(runtime, host) : null
- return { ...outcome, keychainLeftover: leftover }
+ const leftover = record?.keychainLeftover ? await removeKeychainLeftover(runtime, host) : null
+ return { ...outcome, keychainLeftover: leftover }
+ })
}
// Resolves to why the removal failed, or null once no item is left.
@@ -135,7 +152,7 @@ export async function logoutAll(runtime: Runtime): Promise<LoggedOutHost[]> {
for (const host of hosts.values()) {
const record = loginFor(settings, host)
const outcome = await logout(runtime, host)
- const orphan = await file.remove(host)
+ const orphan = await withFileLock(runtime, LOGINS_LOCK, () => file.remove(host))
// Logout already handled a keychain login and a marked leftover.
const swept =
record?.store !== 'keychain' && !record?.keychainLeftover
diff --git a/hog/src/posthog/oauth.test.ts b/hog/src/posthog/oauth.test.ts
new file mode 100644
index 000000000000..9873fd27d563
--- /dev/null
+++ b/hog/src/posthog/oauth.test.ts
@@ -0,0 +1,238 @@
+import { describe, expect, test } from 'bun:test'
+import { createHash } from 'node:crypto'
+
+import { HogError } from '@/core/errors'
+import type { Secrets } from '@/core/runtime'
+import { fakeRuntime, type FakeRuntime } from '@/testing'
+
+import { PostHogApi } from './api'
+import { resolveCredentials, type Credentials } from './credentials'
+import { KeySession } from './key-session'
+import { HOG_CLIENT_ID } from './oauth'
+
+const EU = 'https://eu.posthog.com'
+const START = Date.UTC(2026, 0, 1)
+const SETTINGS_FILE = '/home/test/.config/hog/settings.json'
+const LOCK = /^\/home\/test\/\.config\/hog\/refresh-[0-9a-f]+\.lock$/
+
+// settings.json keeps what isn't secret about the login, and the keychain keeps the tokens.
+function settings(expiresInMs: number): string {
+ const record = {
+ store: 'keychain',
+ type: 'oauth',
+ projectId: '42',
+ host: EU,
+ expiresAt: START + expiresInMs,
+ scopes: ['openid', 'insight:read'],
+ loginId: 'login-1',
+ }
+ return JSON.stringify({ logins: { [EU]: record }, host: EU })
+}
+
+function secret(accessToken: string): string {
+ return JSON.stringify({ accessToken, refreshToken: 'phr_old' })
+}
+
+function stored(
+ accessToken: string,
+ expiresInMs: number
+): { files: Record<string, string>; keychain: Record<string, string> } {
+ return { files: { [SETTINGS_FILE]: settings(expiresInMs) }, keychain: { [EU]: secret(accessToken) } }
+}
+
+function sessionFor(runtime: FakeRuntime, credentials: Credentials): KeySession {
+ return new KeySession(runtime, credentials.key, credentials.source === 'store' ? credentials.storage : null)
+}
+
+const OK = { name: 'Hedgebox' }
+const REJECTED = { status: 401 }
+
+function tokenRequests(runtime: FakeRuntime): FakeRuntime['requests'] {
+ return runtime.requests.filter((request) => request.url === `${EU}/oauth/token/`)
+}
+
+describe('OAuth credentials', () => {
+ test.each([
+ ['renews a token PostHog rejects and sends the request once more', 3_600_000, 0, 'pha_new', 2, OK],
+ ['renews a token about to expire mid-command before it sends', 11 * 60_000, 2 * 60_000, 'pha_new', 1, OK],
+ ['surfaces a second 401 instead of retrying again', 3_600_000, 0, 'pha_also_rejected', 2, REJECTED],
+ ])('a request %s', async (_name, expiresInMs, commandRunsMs, renewedToken, apiCalls, expected) => {
+ const runtime = fakeRuntime({
+ ...stored('pha_old', expiresInMs),
+ respond: (url, _body, authorization) => {
+ if (url === `${EU}/oauth/token/`) {
+ return { status: 200, body: { access_token: renewedToken, expires_in: 3600 } }
+ }
+ return authorization === 'Bearer pha_new'
+ ? { status: 200, body: { name: 'Hedgebox' } }
+ : { status: 401, body: { detail: 'Invalid token' } }
+ },
+ })
+ const api = new PostHogApi(sessionFor(runtime, await resolveCredentials(runtime, {})), runtime.fetch)
+ await runtime.sleep(commandRunsMs)
+
+ const outcome = await api.get<{ name: string }>('').catch((error: unknown) => error)
+
+ expect(outcome).toMatchObject(expected)
+ expect(tokenRequests(runtime)).toHaveLength(1)
+ expect(runtime.requests.filter((request) => request.url.includes('/api/'))).toHaveLength(apiCalls)
+ expect(JSON.parse(runtime.keychain[EU] ?? '{}').accessToken).toBe(renewedToken)
+ })
+
+ test('a 401 that a renewed token gets too stops renewing for the rest of the command', async () => {
+ const runtime = fakeRuntime({
+ ...stored('pha_old', 3_600_000),
+ respond: (url) =>
+ url === `${EU}/oauth/token/`
+ ? { status: 200, body: { access_token: 'pha_new', expires_in: 3600 } }
+ : { status: 401, body: { detail: 'This account is not active' } },
+ })
+ const api = new PostHogApi(sessionFor(runtime, await resolveCredentials(runtime, {})), runtime.fetch)
+
+ const outcomes = [
+ await api.get('').catch((error: unknown) => error),
+ await api.get('').catch((error: unknown) => error),
+ ]
+
+ expect(outcomes).toMatchObject([REJECTED, REJECTED])
+ expect(tokenRequests(runtime)).toHaveLength(1)
+ expect(runtime.requests.filter((request) => request.url.includes('/api/'))).toHaveLength(3)
+ })
+
+ test('a login that replaced this one mid-command stops it instead of sending to its project', async () => {
+ const runtime = fakeRuntime({
+ ...stored('pha_old', 3_600_000),
+ respond: () => ({ status: 401, body: { detail: 'Invalid token' } }),
+ })
+ const api = new PostHogApi(sessionFor(runtime, await resolveCredentials(runtime, {})), runtime.fetch)
+ const replaced = JSON.parse(settings(3_600_000))
+ replaced.logins[EU] = { ...replaced.logins[EU], projectId: '99', loginId: 'login-2' }
+ runtime.files[SETTINGS_FILE] = JSON.stringify(replaced)
+ runtime.keychain[EU] = secret('pha_other')
+
+ const outcome = await api.get('').catch((error: unknown) => error)
+
+ expect(outcome).toMatchObject({ code: 'login_changed' })
+ expect(tokenRequests(runtime)).toEqual([])
+ })
+
+ test('a stored personal API key that PostHog rejects is sent only once', async () => {
+ const record = { store: 'keychain', type: 'personal_api_key', projectId: '42', host: EU }
+ const runtime = fakeRuntime({
+ files: { [SETTINGS_FILE]: JSON.stringify({ logins: { [EU]: record }, host: EU }) },
+ keychain: { [EU]: JSON.stringify({ apiKey: 'phx_deleted' }) },
+ respond: () => ({ status: 401, body: { detail: 'Invalid personal API key' } }),
+ })
+ const api = new PostHogApi(sessionFor(runtime, await resolveCredentials(runtime, {})), runtime.fetch)
+
+ const outcome = await api.get('').catch((error: unknown) => error)
+
+ expect(outcome).toMatchObject(REJECTED)
+ expect(runtime.requests).toHaveLength(1)
+ })
+
+ test('renew a token about to expire, keeping the refresh token PostHog did not rotate', async () => {
+ const runtime = fakeRuntime({
+ ...stored('pha_old', 30_000),
+ respond: () => ({ status: 200, body: { access_token: 'pha_new', expires_in: 3600, scope: 'openid' } }),
+ })
+
+ const credentials = await resolveCredentials(runtime, {})
+
+ expect(credentials.key).toMatchObject({ token: 'pha_new', projectId: '42' })
+ expect(credentials.key.status()).toMatchObject({ kind: 'oauth', scopes: ['openid'] })
+ expect(tokenRequests(runtime).map((request) => request.body)).toEqual([
+ { grant_type: 'refresh_token', refresh_token: 'phr_old', client_id: HOG_CLIENT_ID },
+ ])
+ expect(JSON.parse(runtime.keychain[EU] ?? '{}')).toEqual({ accessToken: 'pha_new', refreshToken: 'phr_old' })
+ expect(JSON.parse(runtime.files[SETTINGS_FILE] ?? '{}').logins[EU]).toMatchObject({
+ expiresAt: START + 3_600_000,
+ scopes: ['openid'],
+ loginId: 'login-1',
+ })
+ expect(Object.keys(runtime.files).filter((path) => LOCK.test(path))).toEqual([])
+ })
+
+ test('retry a renewal whose answer got lost, and keep the rotated refresh token', async () => {
+ let calls = 0
+ const runtime = fakeRuntime({
+ ...stored('pha_old', 30_000),
+ respond: () => {
+ calls += 1
+ if (calls === 1) {
+ throw new Error('connection reset')
+ }
+ return { status: 200, body: { access_token: 'pha_new', refresh_token: 'phr_new', expires_in: 3600 } }
+ },
+ })
+
+ const credentials = await resolveCredentials(runtime, {})
+
+ expect(credentials.key).toMatchObject({ token: 'pha_new' })
+ expect(tokenRequests(runtime)).toHaveLength(2)
+ expect(JSON.parse(runtime.keychain[EU] ?? '{}')).toEqual({ accessToken: 'pha_new', refreshToken: 'phr_new' })
+ })
+
+ test('use a token with time left as it is', async () => {
+ const runtime = fakeRuntime({
+ ...stored('pha_old', 3_600_000),
+ })
+
+ expect((await resolveCredentials(runtime, {})).key).toMatchObject({ token: 'pha_old' })
+ expect(runtime.requests).toEqual([])
+ })
+
+ test.each([
+ ['a lock its owner left behind', JSON.stringify({ id: 'theirs', createdAt: START - 179_000 }), 1_000],
+ ['a lock nobody can read', '', 180_000],
+ ])('take over %s, and use the token its owner stored', async (_name, lockContents, minimumWaitMs) => {
+ // The first read finds the expiring token. By the time hog holds the lock, settings.json and
+ // the keychain have the login the other process renewed before it died.
+ let reads = 0
+ const secrets = (): Secrets => ({
+ get: async () => secret(reads++ === 0 ? 'pha_old' : 'pha_theirs'),
+ set: async () => {},
+ delete: async () => true,
+ })
+ const runtime = fakeRuntime({ files: { [SETTINGS_FILE]: settings(30_000) }, secrets })
+ const readFile = runtime.readFile
+ let settingsReads = 0
+ runtime.readFile = async (path) =>
+ path === SETTINGS_FILE && settingsReads++ > 0 ? settings(3_600_000) : readFile(path)
+ const lock = `/home/test/.config/hog/refresh-${createHash('sha256').update(EU).digest('hex').slice(0, 16)}.lock`
+ runtime.files[lock] = lockContents
+
+ const credentials = await resolveCredentials(runtime, {})
+
+ expect(credentials.key).toMatchObject({ token: 'pha_theirs' })
+ expect(tokenRequests(runtime)).toEqual([])
+ expect(runtime.files[lock]).toBeUndefined()
+ expect(runtime.now() - START).toBeGreaterThan(minimumWaitMs)
+ })
+
+ test('a revoked refresh token says to log in again', async () => {
+ const runtime = fakeRuntime({
+ ...stored('pha_old', 30_000),
+ respond: () => ({ status: 400, body: { error: 'invalid_grant' } }),
+ })
+
+ const error = await resolveCredentials(runtime, {}).catch((caught: unknown) => caught)
+
+ expect(error).toBeInstanceOf(HogError)
+ expect((error as HogError).code).toBe('session_expired')
+ })
+
+ test('a login for another host than posthog.json names fails before hog renews it', async () => {
+ const runtime = fakeRuntime({
+ ...stored('pha_old', 30_000),
+ respond: () => ({ status: 200, body: { access_token: 'pha_new', expires_in: 3600 } }),
+ })
+
+ const error = await resolveCredentials(runtime, { configHost: 'https://us.posthog.com' }).catch(
+ (caught: unknown) => caught
+ )
+
+ expect((error as HogError).code).toBe('host_mismatch')
+ expect(tokenRequests(runtime)).toEqual([])
+ })
+})
diff --git a/hog/src/posthog/oauth.ts b/hog/src/posthog/oauth.ts
new file mode 100644
index 000000000000..6d44b8e43f1e
--- /dev/null
+++ b/hog/src/posthog/oauth.ts
@@ -0,0 +1,227 @@
+import { createHash, randomUUID } from 'node:crypto'
+
+import { HogError } from '@/core/errors'
+import { withFileLock } from '@/core/file-lock'
+import type { Runtime } from '@/core/runtime'
+import type { OAuthSecret, StoreChoice } from '@/posthog/credential-store/types'
+
+import type { AccessKey, AccessKeyStatus, AccessKeyStorage, LogoutOutcome } from './access-key'
+import { sendRequest, type HttpResponse } from './api'
+import { hostKey, hostUrl } from './host'
+import type { LoginRecord } from './settings'
+
+// hog's CIMD client ID: the URL of its client metadata document, which PostHog fetches.
+export const HOG_CLIENT_ID = 'https://posthog.com/.well-known/oauth/hog/client-metadata.json'
+
+const REQUEST_TIMEOUT_MS = 30_000
+// Refresh this long before the access token expires, so it doesn't expire during a command.
+const REFRESH_MARGIN_MS = 10 * 60_000
+
+export interface TokenResponse {
+ access_token?: string
+ refresh_token?: string
+ expires_in?: number
+ scope?: string
+ scoped_teams?: number[]
+}
+
+export function oauthPost(
+ runtime: Runtime,
+ host: string,
+ path: string,
+ form: Record<string, string>,
+ timeoutMs = REQUEST_TIMEOUT_MS
+): Promise<HttpResponse> {
+ return sendRequest(runtime.fetch, hostUrl(host, path), {
+ method: 'POST',
+ form,
+ timeoutMs,
+ })
+}
+
+interface OAuthLoginFields {
+ host: string
+ projectId: string
+ accessToken: string
+ refreshToken: string
+ // Epoch milliseconds after which the access token stops working.
+ expiresAt: number
+ scopes: string[]
+ // A random id the login keeps for life. The refresh token changes on each renewal, so it can't
+ // name the login.
+ loginId: string
+}
+
+// Serializes the processes that renew or remove the login to one host.
+export function withLoginLock<T>(runtime: Runtime, host: string, work: () => Promise<T>): Promise<T> {
+ // By origin, so `https://eu.posthog.com/` and `https://eu.posthog.com` take the same lock.
+ const name = createHash('sha256').update(hostKey(host)).digest('hex').slice(0, 16)
+ return withFileLock(runtime, `refresh-${name}.lock`, work)
+}
+
+// What `hog auth login` gets from the OAuth device grant. The access token works in one project.
+export class OAuthLogin implements AccessKey {
+ readonly host: string
+ readonly projectId: string
+ readonly accessToken: string
+ readonly refreshToken: string
+ readonly expiresAt: number
+ readonly scopes: string[]
+ readonly loginId: string
+
+ constructor(fields: OAuthLoginFields) {
+ this.host = fields.host
+ this.projectId = fields.projectId
+ this.accessToken = fields.accessToken
+ this.refreshToken = fields.refreshToken
+ this.expiresAt = fields.expiresAt
+ this.scopes = fields.scopes
+ this.loginId = fields.loginId
+ }
+
+ // Fields the response leaves out keep this login's values, so a refresh that doesn't rotate the
+ // refresh token keeps the old one. A new login gets a new id.
+ static fromTokens(
+ runtime: Runtime,
+ body: TokenResponse,
+ previous: Pick<OAuthLoginFields, 'host' | 'projectId' | 'refreshToken' | 'scopes'> & { loginId?: string }
+ ): OAuthLogin {
+ if (!body.access_token || body.expires_in === undefined) {
+ throw new HogError(
+ 'unexpected_response',
+ 'PostHog answered without an access token.',
+ 'Run `hog auth login` to log in again.'
+ )
+ }
+ return new OAuthLogin({
+ host: previous.host,
+ projectId: previous.projectId,
+ accessToken: body.access_token,
+ refreshToken: body.refresh_token ?? previous.refreshToken,
+ expiresAt: runtime.now() + body.expires_in * 1000,
+ scopes: body.scope ? body.scope.split(' ').filter(Boolean) : previous.scopes,
+ loginId: previous.loginId ?? randomUUID(),
+ })
+ }
+
+ get token(): string {
+ return this.accessToken
+ }
+
+ get loginKey(): string {
+ return this.loginId
+ }
+
+ private hasTimeLeft(runtime: Runtime): boolean {
+ return this.expiresAt - runtime.now() > REFRESH_MARGIN_MS
+ }
+
+ // When PostHog rotates refresh tokens, it revokes the whole login if a rotated refresh token is
+ // used again, so two hog processes must never refresh at once: the refresh runs under a lock
+ // file, and re-reads the stored login inside it to pick up a token another process just stored.
+ async fresh(runtime: Runtime, storage: AccessKeyStorage, rejectedToken?: string): Promise<AccessKey> {
+ // Another request or process may have renewed the rejected token already, so it only counts
+ // while it is still the stored one.
+ const needsRenewal = (login: OAuthLogin): boolean =>
+ rejectedToken === undefined ? !login.hasTimeLeft(runtime) : login.accessToken === rejectedToken
+ if (!needsRenewal(this)) {
+ return this
+ }
+ return withLoginLock(runtime, this.host, async () => {
+ const current = await storage.reread()
+ if (!(current instanceof OAuthLogin)) {
+ throw new HogError(
+ 'not_authenticated',
+ 'You logged out of hog.',
+ 'Run `hog auth login` to log in again.'
+ )
+ }
+ // A new login, possibly to another project, replaced this one. Using it would send the
+ // rest of the command to a project it didn't plan against.
+ if (current.loginId !== this.loginId) {
+ throw new HogError(
+ 'login_changed',
+ 'You logged in again while this command ran.',
+ 'Run the command again to use the new login.'
+ )
+ }
+ if (!needsRenewal(current)) {
+ return current
+ }
+ const renewed = await current.refresh(runtime).catch((error: unknown) => {
+ // A lost answer may hide a rotation that already happened. PostHog takes the old
+ // refresh token again during its grace period, so one retry recovers the new tokens.
+ if (error instanceof HogError && error.code === 'network_error') {
+ return current.refresh(runtime)
+ }
+ throw error
+ })
+ try {
+ await storage.save(renewed)
+ } catch {
+ // PostHog already replaced the refresh token, so a lost write ends the login once the
+ // grace period passes. One more try covers a keychain that failed for a moment.
+ await storage.save(renewed)
+ }
+ return renewed
+ })
+ }
+
+ // PostHog issued this login moments ago, so there is nothing to check.
+ async verify(): Promise<OAuthLogin> {
+ return this
+ }
+
+ private async refresh(runtime: Runtime): Promise<OAuthLogin> {
+ const response = await oauthPost(runtime, this.host, 'oauth/token/', {
+ grant_type: 'refresh_token',
+ refresh_token: this.refreshToken,
+ client_id: HOG_CLIENT_ID,
+ })
+ const body = (response.json ?? {}) as TokenResponse & { error?: string }
+ if (response.ok) {
+ return OAuthLogin.fromTokens(runtime, body, this)
+ }
+ if (body.error === 'invalid_grant') {
+ throw new HogError(
+ 'session_expired',
+ 'Your hog login expired or was revoked.',
+ 'Run `hog auth login` to log in again.'
+ )
+ }
+ throw new HogError(
+ 'refresh_failed',
+ `PostHog didn't renew your login: it answered with HTTP ${response.status}.`,
+ 'Run the command again. If it keeps failing, run `hog auth login`.'
+ )
+ }
+
+ status(): AccessKeyStatus {
+ return { kind: 'oauth', scopes: this.scopes, expiresAt: this.expiresAt }
+ }
+
+ // Revoking the refresh token ends this login: PostHog revokes its access tokens with it.
+ async logout(runtime: Runtime): Promise<LogoutOutcome> {
+ let revoked = false
+ try {
+ const response = await oauthPost(runtime, this.host, 'oauth/revoke/', {
+ token: this.refreshToken,
+ token_type_hint: 'refresh_token',
+ client_id: HOG_CLIENT_ID,
+ })
+ revoked = response.ok
+ } catch {
+ revoked = false
+ }
+ return { revoked, revokeUrl: null }
+ }
+
+ secret(): OAuthSecret {
+ return { accessToken: this.accessToken, refreshToken: this.refreshToken }
+ }
+
+ record(store: StoreChoice): LoginRecord {
+ const { host, projectId, expiresAt, scopes, loginId } = this
+ return { store, type: 'oauth', projectId, host, expiresAt, scopes, loginId }
+ }
+}
diff --git a/hog/src/posthog/settings.ts b/hog/src/posthog/settings.ts
index ec5c0869b1d1..25a3c0970a01 100644
--- a/hog/src/posthog/settings.ts
+++ b/hog/src/posthog/settings.ts
@@ -5,12 +5,11 @@ import type { StoreChoice } from '@/posthog/credential-store/types'
import { hostKey, type HostKey } from './host'
// What settings.json keeps about the login to one host: everything except its secrets.
-export interface LoginRecord {
+interface LoginRecordBase {
// hog probes the keychain only at login, because a probe can open a dialog. Each host keeps its
// own answer, so a login over SSH that had to use the file doesn't hide a keychain login to
// another host.
store: StoreChoice
- type: 'personal_api_key'
projectId: string
// The host the login was made for, with the path a self-hosted PostHog sits under. The login is
// keyed by origin, so a posthog.json path on the same origin can't send it elsewhere.
@@ -20,6 +19,11 @@ export interface LoginRecord {
keychainLeftover?: true
}
+export type LoginRecord =
+ | (LoginRecordBase & { type: 'personal_api_key' })
+ // `expiresAt` is in epoch milliseconds, for the access token.
+ | (LoginRecordBase & { type: 'oauth'; expiresAt: number; scopes: string[]; loginId: string })
+
// What `hog auth login` decided, kept so later runs don't decide again. Nothing in it is secret.
export interface HogSettings {
logins?: Partial<Record<HostKey, LoginRecord>>
@@ -37,14 +41,28 @@ function settingsPath(runtime: Runtime): string {
function parseLoginRecord(origin: string, value: unknown): LoginRecord | undefined {
const item = value as Record<string, unknown> | null
if (
- (item?.store === 'keychain' || item?.store === 'file') &&
- item.type === 'personal_api_key' &&
- typeof item.projectId === 'string' &&
- typeof item.host === 'string' &&
- hostKey(item.host) === hostKey(origin)
+ (item?.store !== 'keychain' && item?.store !== 'file') ||
+ typeof item.projectId !== 'string' ||
+ typeof item.host !== 'string' ||
+ hostKey(item.host) !== hostKey(origin)
+ ) {
+ return undefined
+ }
+ const { store, projectId, host } = item
+ const base: LoginRecordBase =
+ item.keychainLeftover === true ? { store, projectId, host, keychainLeftover: true } : { store, projectId, host }
+ if (item.type === 'personal_api_key') {
+ return { ...base, type: 'personal_api_key' }
+ }
+ if (
+ item.type === 'oauth' &&
+ typeof item.expiresAt === 'number' &&
+ typeof item.loginId === 'string' &&
+ Array.isArray(item.scopes) &&
+ item.scopes.every((scope) => typeof scope === 'string')
) {
- const record: LoginRecord = { store: item.store, type: item.type, projectId: item.projectId, host: item.host }
- return item.keychainLeftover === true ? { ...record, keychainLeftover: true } : record
+ const { expiresAt, loginId } = item
+ return { ...base, type: 'oauth', expiresAt, scopes: item.scopes, loginId }
}
return undefined
}
diff --git a/hog/src/testing.ts b/hog/src/testing.ts
index 358a812fbcd8..9b33ef8f2ff8 100644
--- a/hog/src/testing.ts
+++ b/hog/src/testing.ts
@@ -20,7 +20,7 @@ export interface FakeRuntimeOptions {
answers?: string[]
// Answers every API request. Without it, requests fail with HTTP 500. A string body is sent
// as is, for JSON that JSON.stringify can't produce.
- respond?: (url: string, body: unknown) => { status: number; body: unknown }
+ respond?: (url: string, body: unknown, authorization: string | null) => { status: number; body: unknown }
telemetryToken?: string
// The MCP tool catalog `hog api` loads. Without it, loading the catalog fails the test.
apiTools?: ApiToolLibrary
@@ -58,6 +58,15 @@ function fakePrompts(answers: string[]): Prompts {
}
}
+// Requests carry JSON, except OAuth requests, which are form encoded.
+function parseBody(body: string): unknown {
+ try {
+ return JSON.parse(body)
+ } catch {
+ return Object.fromEntries(new URLSearchParams(body))
+ }
+}
+
function memorySecrets(items: Record<string, string>): Secrets {
return {
get: async (name) => items[name] ?? null,
@@ -148,9 +157,13 @@ export function fakeRuntime(options: FakeRuntimeOptions = {}): FakeRuntime {
},
fetch: (async (input: string | URL | Request, init?: RequestInit) => {
const url = String(input)
- const body = init?.body === undefined ? undefined : JSON.parse(String(init.body))
+ const body = init?.body === undefined ? undefined : parseBody(String(init.body))
requests.push({ method: init?.method ?? 'GET', url, body })
- const reply = options.respond?.(url, body) ?? { status: 500, body: { detail: 'no fake response' } }
+ const authorization = new Headers(init?.headers).get('authorization')
+ const reply = options.respond?.(url, body, authorization) ?? {
+ status: 500,
+ body: { detail: 'no fake response' },
+ }
const text = typeof reply.body === 'string' ? reply.body : JSON.stringify(reply.body)
return new Response(text, { status: reply.status })
}) as typeof fetch,
@@ -198,6 +211,13 @@ export function fakeRuntime(options: FakeRuntimeOptions = {}): FakeRuntime {
writePrivateFile: async (path, contents) => {
files[path] = contents
},
+ createFile: async (path, contents) => {
+ if (path in files) {
+ return false
+ }
+ files[path] = contents
+ return true
+ },
removeFile: async (path) => {
delete files[path]
},
diff --git a/posthog/api/oauth/device.py b/posthog/api/oauth/device.py
index ba9093e3317e..5139f1739ad1 100644
--- a/posthog/api/oauth/device.py
+++ b/posthog/api/oauth/device.py
@@ -212,10 +212,16 @@ def device_token_response(create_token_response: Any, request: HttpRequest, devi
if not cache.add(poll_key, True, timeout=1):
return _error_response(rfc8628_errors.SlowDownError())
with transaction.atomic():
- grant = OAuthDeviceGrant.objects.select_for_update().filter(device_code=device_code).first()
- # Checked before any status answer, so a poll by another client neither learns the status
- # nor moves `last_checked`. The post-token hook checks the authenticated client again.
- if grant is None or _presented_client_id(request) != grant.client_id:
+ # Filtered on the presented client too, so a poll that names another client locks nothing,
+ # and varying the client can't get past the per-second limit to pile up locks on the row.
+ # A poll by another client neither learns the status nor moves `last_checked`. The
+ # post-token hook checks the authenticated client again.
+ grant = (
+ OAuthDeviceGrant.objects.select_for_update()
+ .filter(device_code=device_code, client_id=_presented_client_id(request) or "")
+ .first()
+ )
+ if grant is None:
return _error_response(rfc6749_errors.InvalidGrantError(description="The device code is not valid."))
if grant.status in (OAuthDeviceGrant.AUTHORIZATION_PENDING, OAuthDeviceGrant.AUTHORIZED) and (
timezone.now() >= grant.expires
diff --git a/posthog/api/oauth/test_device.py b/posthog/api/oauth/test_device.py
index bece53b19618..fd91373b07e1 100644
--- a/posthog/api/oauth/test_device.py
+++ b/posthog/api/oauth/test_device.py
@@ -188,6 +188,26 @@ class TestOAuthDeviceGrant(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["error"], expected)
+ def test_revoking_a_refresh_token_rotation_replaced_ends_the_login(self) -> None:
+ with time_machine.travel(START, tick=False) as clock:
+ started = self._start()
+ self._approve(started["user_code"])
+ clock.shift(timedelta(seconds=6))
+ first = self._poll(started["device_code"]).json()
+ refresh_body = {
+ "grant_type": "refresh_token",
+ "refresh_token": first["refresh_token"],
+ "client_id": "hog-device-client",
+ }
+ refreshed = self.client.post("/oauth/token/", urlencode(refresh_body), content_type=FORM).json()
+
+ revoke_body = {"token": first["refresh_token"], "client_id": "hog-device-client"}
+ revoked = self.client.post("/oauth/revoke/", urlencode(revoke_body), content_type=FORM)
+
+ self.assertEqual(revoked.status_code, status.HTTP_200_OK, revoked.content)
+ self.assertFalse(OAuthAccessToken.objects.filter(token=refreshed["access_token"]).exists())
+ self.assertFalse(OAuthRefreshToken.objects.filter(token=refreshed["refresh_token"], revoked=None).exists())
+
def test_only_the_client_that_started_the_grant_can_redeem_it(self) -> None:
OAuthApplication.objects.create(
name="other",
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 373f039fe7cd..660e6fc8a578 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -1147,7 +1147,8 @@ class OAuthValidator(OAuth2Validator):
# A rotating family holds every access token of one login, so revoking it ends only that
# login. A token already rotated away still ends its family: during the grace period it can
# still refresh.
- if rt and self._is_dynamic_client(request) and self.rotate_refresh_token(request):
+ dynamic_or_device = self._is_dynamic_client(request) or self._is_device_client(request)
+ if rt and dynamic_or_device and self.rotate_refresh_token(request):
revoke_oauth_refresh_family(rt)
return
# A non-rotating token can't be traced to its access tokens, so the whole connection goes.