~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
134 lines · 8.5 KB Raw History
// tranquil, in Docker, from the image `node bench.mjs --setup` builds from
// its pinned commit (bench/impls.json), on a fresh PostgreSQL, configured as
// lib/impls.mjs configures it, plus what a compatibility run needs.

import { spawnSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { join } from 'node:path'
import { Browser } from '../oauth.mjs'
import { dockerPort, imageId, pins, shOk, startPostgres, tranquilCreateArgs, tranquilEnv, tranquilOwnEnv } from '../impls.mjs'
import { DOCKER_NEEDS, container } from './common.mjs'

const TRANQUIL = pins.implementations.tranquil
/// The origin tranquil names itself by: `https://<PDS_HOSTNAME>`, its
/// issuer, its DID documents' endpoint and the `htu` its DPoP proofs must
/// name (crates/tranquil-config/src/lib.rs:583-586,
/// crates/tranquil-oauth-server/src/endpoints/token/grants.rs:100), though
/// the harness reaches it on a loopback port (spec/COMPAT.md, "Its own
/// address").
const NAMED = 'https://localhost'

export default {
  about: `tranquil ${TRANQUIL.release} (${TRANQUIL.repo} at ${TRANQUIL.commit.slice(0, 7)}), its image built by \`node bench.mjs --setup\`, on PostgreSQL, in Docker`,
  pageApi: false,
  own: false,
  unsupported: {
    rotationKey: 'tranquil signs each account\'s PLC operations with that account\'s own signing key, which it holds and which is always one of its rotation keys; its one operator key, PLC_ROTATION_KEY, is a public did:key it cannot sign with (crates/tranquil-config/src/lib.rs:648-653, crates/tranquil-pds/src/plc/mod.rs:368-377): the harness has no key to sign an operation of its own with',
    hostname: 'tranquil names itself https://<PDS_HOSTNAME>, which must be localhost for the reference\'s server DID, and with that hostname it asks no crawler to crawl (crates/tranquil-pds/src/crawlers.rs:45-48)',
    clientFetch: 'tranquil fetches a client document from the client_id\'s own URL (crates/tranquil-oauth/src/client.rs:251); it has no mapping of origins to the harness\'s web, as PDS_OAUTH_CLIENT_FETCH is',
    narrowScope: 'tranquil\'s consent takes the scopes approved (crates/tranquil-oauth-server/src/endpoints/authorize/consent.rs:87), but the sign-in hook (compat/README.md, "The OAuth sign-in hook") carries no scope to approve: the scope asked is approved',
    adminPassword: 'tranquil has no admin password: an admin is an account marked so in its database, calling with its own access token (crates/tranquil-pds/src/auth/extractor.rs:170, 214)',
    mail: 'tranquil sends mail only to an SMTP relay (MAIL_SMARTHOST_HOST, crates/tranquil-config/src/lib.rs:1152) and keeps none to read back; with no sender address its email is off',
    restart: 'a container keeps the environment it was made with: no restart with another',
    address: 'tranquil names itself https://localhost, reached in the run on a loopback port (spec/COMPAT.md, "Its own address"); the atproto OAuth client library refuses an https resource on a loopback host, so it cannot sign in to it here',
    lexiconAuthority: 'tranquil looks a permission set\'s lexicon up in DNS, as `_lexicon.<authority>` (crates/tranquil-scopes/src/permission_set.rs:297), with no setting naming one DID for every NSID, as PDS_LEXICON_AUTHORITY_DID does; the harness serves no DNS',
  },
  port: dockerPort,
  readyMs: 120_000,
  /// A password tranquil's rules take (spec/COMPAT.md, "Password rules"):
  /// 8 to 256 bytes, with a lowercase and an uppercase letter and a digit
  /// (crates/tranquil-pds/src/validation/mod.rs:275-299), made from `p`:
  /// `p` itself if it fits, else `p` (or, past 240 bytes, its SHA-256 in
  /// hex) with `-Aa1` after it.
  passwordFor(p) {
    const bytes = Buffer.byteLength(p)
    if (bytes >= 8 && bytes <= 256 && /[a-z]/.test(p) && /[A-Z]/.test(p) && /[0-9]/.test(p)) return p
    return `${bytes <= 240 ? p : createHash('sha256').update(p).digest('hex')}-Aa1`
  },
  async info() {
    const db = pins.images[TRANQUIL.needs[0]]
    return { version: TRANQUIL.release, source: `${TRANQUIL.repo} at ${TRANQUIL.commit}, image ${TRANQUIL.tag} (${await imageId(TRANQUIL.tag)}) built with its own ${TRANQUIL.dockerfile}; PostgreSQL ${db.image} (${db.release})`, config: '' }
  },
  async start(o) {
    for (const image of [TRANQUIL.tag, pins.images[TRANQUIL.needs[0]].image]) if (!(await imageId(image))) throw new Error(`tranquil: no Docker image ${image}; ${DOCKER_NEEDS}`)
    const id = `compat-tranquil-${process.pid}-${Date.now()}`
    const store = `${id}-db`
    const pds = `${id}-pds`
    const teardown = () => {
      spawnSync('docker', ['rm', '-f', '-v', pds])
      spawnSync('docker', ['rm', '-f', '-v', store])
      spawnSync('docker', ['network', 'rm', id])
    }
    let env
    try {
      await shOk('docker', ['network', 'create', id])
      const db = await startPostgres(id, store)
      // The harness's setup, as far as tranquil takes it
      // (crates/tranquil-config/src/lib.rs): the reference's hostname, so
      // its server DID; the handle domains, which it names with no
      // leading dot; the reference's recovery key, its one operator key,
      // listed first in each DID it makes; invites and rate limits on or
      // off. No AppView setting: it proxies by the `atproto-proxy` header,
      // resolving the DID it names.
      env = {
        ...tranquilEnv,
        ...tranquilOwnEnv({ plcUrl: o.plc, db }),
        PDS_HOSTNAME: 'localhost',
        PDS_USER_HANDLE_DOMAINS: 'test,example',
        PLC_ROTATION_KEY: o.recoveryKey,
        INVITE_CODE_REQUIRED: String(o.invites),
        DISABLE_RATE_LIMITING: String(!o.limits),
      }
      await shOk('docker', tranquilCreateArgs({ name: pds, network: id, port: o.port, env }))
    } catch (e) {
      teardown()
      throw e
    }
    const url = `http://127.0.0.1:${o.port}`
    return {
      server: container(pds, env, join(o.logDir, 'server.log'), join(o.logDir, 'server.err'), teardown),
      url,
      publicUrl: NAMED,
      fronted: true,
      recoveryKey: o.recoveryKey,
      // Each account's own signing key (see `unsupported`).
      rotationKey: null,
      plcSigner: null,
      admin: null,
      takeMail: () => [],
    }
  },
  /// tranquil's authorization page, a script calling its JSON endpoints
  /// (crates/tranquil-oauth-server/src/endpoints/authorize/), as its script
  /// calls them: sign-in posts `request_uri`, `username` and `password` to
  /// /oauth/authorize, which answers the next page as `redirect_uri`: the
  /// consent page, whose scopes /oauth/authorize/consent answers and
  /// approves, or at once the redirect. That redirect,
  /// /oauth/authorize/redirect, answers the 303 to the client. Refusing,
  /// /oauth/authorize/deny answers the client's URL with
  /// `error=access_denied` as JSON, which the script navigates to: here a
  /// 303 there, as the browser goes.
  async signIn(account, authorizeUrl, consent) {
    const at = (u) => new URL(u, NAMED).href
    const page = new URL(authorizeUrl)
    const requestUri = page.searchParams.get('request_uri')
    const b = new Browser()
    const call = (path, body) => b.request(at(path), { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json', origin: page.origin, referer: page.href }, body: JSON.stringify(body) })
    await b.navigate(page.href)
    if (!consent.approve) {
      const denied = await call('/oauth/authorize/deny', { request_uri: requestUri })
      if (denied.status !== 200 || typeof denied.json?.redirect_uri !== 'string') return denied
      return { status: 303, headers: { location: denied.json.redirect_uri }, text: '', json: undefined, data: {} }
    }
    let next = await call('/oauth/authorize', { request_uri: requestUri, username: account.identifier, password: account.password, remember_device: false })
    if (next.status !== 200 || typeof next.json?.redirect_uri !== 'string') return next
    if (new URL(next.json.redirect_uri, NAMED).pathname.startsWith('/app/oauth/consent')) {
      const shown = await b.request(at(`/oauth/authorize/consent?${new URLSearchParams({ request_uri: requestUri })}`), { headers: { accept: 'application/json', referer: page.href } })
      if (shown.status !== 200 || !Array.isArray(shown.json?.scopes)) return shown
      const approved = [...shown.json.scopes.map((s) => s.scope), ...(shown.json.permission_sets ?? []).map((s) => s.include_scope)]
      next = await call('/oauth/authorize/consent', { request_uri: requestUri, approved_scopes: approved, remember: false })
      if (next.status !== 200 || typeof next.json?.redirect_uri !== 'string') return next
    }
    return b.navigate(at(next.json.redirect_uri), { site: 'same-origin', referer: page.href })
  },
}