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
8 changes: 8 additions & 0 deletions packages/cli/src/backend/ProjectStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,24 @@ export interface ProjectHandle {
readonly backend: ProjectBackend;
/** Only present when `backend` is "github"; `owner/name`. */
readonly repo?: string;
/**
* The host recorded at init; absent on projects that predate the key, which
* fall back to the git remote resolved in `root`.
*/
readonly host?: string;
}

export class ProjectStore extends Context.Service<
ProjectStore,
{
/** Whether `directory` already holds wayful state, checked before any remote work. */
readonly projectExists: (directory: string) => Effect.Effect<boolean, WayfulError>;
readonly initProject: (options: {
readonly directory: string;
readonly description: string;
readonly backend?: ProjectBackend;
readonly repo?: string;
readonly host?: string;
}) => Effect.Effect<void, WayfulError>;
readonly openProject: (
hint: Option.Option<string>,
Expand Down
13 changes: 13 additions & 0 deletions packages/cli/src/backend/filesystem/decode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ const fail = (message: string): never => {
// leading/trailing/doubled); repo names additionally allow `.` and `_`.
export const REPO_PATTERN = /^[A-Za-z0-9](?:-?[A-Za-z0-9])*\/[A-Za-z0-9._-]+$/;

// A GitHub host: a DNS name, optionally dotted (`github.example.com`), never a
// URL, port, or path.
export const HOST_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/;

export function decodeProjectMetadata(data: unknown): ProjectMetadata {
if (!data || typeof data !== "object" || Array.isArray(data)) fail("malformed project metadata.");
const record = data as Record<string, unknown>;
Expand All @@ -26,6 +30,7 @@ export function decodeProjectMetadata(data: unknown): ProjectMetadata {
"description",
"backend",
"repo",
"host",
"created_at",
"updated_at",
]);
Expand All @@ -50,13 +55,21 @@ export function decodeProjectMetadata(data: unknown): ProjectMetadata {
} else if (backend === "github") {
fail(`project backend "github" requires repo.`);
}
let host: string | undefined;
if (record.host !== undefined) {
if (backend !== "github") fail(`project host requires backend "github".`);
if (typeof record.host !== "string" || !HOST_PATTERN.test(record.host))
fail(`project host must be a valid hostname.`);
host = record.host as string;
}
const createdAt = timestamp(record.created_at, "project created_at");
const updatedAt = timestamp(record.updated_at, "project updated_at");
return {
format_version: CURRENT_FORMAT_VERSION,
description: record.description as string,
backend,
repo,
host,
created_at: createdAt,
updated_at: updatedAt,
};
Expand Down
60 changes: 60 additions & 0 deletions packages/cli/src/backend/filesystem/layer/ops/project-type.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,4 +107,64 @@ describe("FileSystemBackend: project and type round-trips", () => {
expect(project.backend).toBe("github");
expect(project.repo).toBe("acme/widgets");
});

test("initProject persists the github host, and openProject round-trips it", async () => {
const directory = await temporaryDirectory();
const project = await run(
Effect.gen(function* () {
const b = yield* backend();
yield* b.initProject({
directory,
description: "",
backend: "github",
repo: "acme/widgets",
host: "github.example.com",
});
return yield* b.openProject(Option.some(directory));
}),
);
expect(project.backend).toBe("github");
expect(project.host).toBe("github.example.com");
});

test("openProject tolerates a github project with no recorded host, for the fallback", async () => {
const directory = await temporaryDirectory();
const project = await run(
Effect.gen(function* () {
const b = yield* backend();
yield* b.initProject({
directory,
description: "",
backend: "github",
repo: "acme/widgets",
});
return yield* b.openProject(Option.some(directory));
}),
);
expect(project.host).toBeUndefined();
});

test("rejects a host on a filesystem project and a malformed host", async () => {
const cases: Array<{
readonly backend: "filesystem" | "github";
readonly host: string;
readonly repo?: string;
}> = [
{ backend: "filesystem", host: "github.com" },
{ backend: "github", host: "has a space", repo: "acme/widgets" },
{ backend: "github", host: "", repo: "acme/widgets" },
];
for (const { backend: targetBackend, host, repo } of cases) {
const directory = await temporaryDirectory();
const error = await runFailure(
Effect.gen(function* () {
const b = yield* backend();
yield* b.initProject({ directory, description: "", backend: targetBackend, repo, host });
return yield* b.openProject(Option.some(directory));
}),
);
expect(error).toBeInstanceOf(WayfulError);
expect((error as WayfulError).message).toContain("host");
}
});
});
22 changes: 22 additions & 0 deletions packages/cli/src/backend/filesystem/layer/ops/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,37 @@ export function makeProjectOps(fs: FileSystem.FileSystem, path: Path.Path) {
return yield* fail("no Wayful project found; run 'wayful init' first.");
});

// Walks upward like `discoverProjectRoot`, so `init` refuses anywhere inside
// an existing project rather than nesting a second one.
const projectExists = (directory: string): Effect.Effect<boolean, WayfulError> =>
Effect.gen(function* () {
let current = path.resolve(directory);
while (true) {
const exists = yield* fs
.exists(path.join(current, ".wayful"))
.pipe(Effect.mapError(accessError));
if (exists) return true;
const parent = path.dirname(current);
if (parent === current) return false;
current = parent;
}
});

return {
projectExists,

initProject: ({
directory,
description,
backend = "filesystem",
repo,
host,
}: {
readonly directory: string;
readonly description: string;
readonly backend?: ProjectBackend;
readonly repo?: string;
readonly host?: string;
}) =>
Effect.gen(function* () {
const root = path.resolve(directory);
Expand All @@ -61,6 +81,7 @@ export function makeProjectOps(fs: FileSystem.FileSystem, path: Path.Path) {
description,
backend,
...(repo !== undefined ? { repo } : {}),
...(host !== undefined ? { host } : {}),
created_at: now,
updated_at: now,
}),
Expand Down Expand Up @@ -91,6 +112,7 @@ export function makeProjectOps(fs: FileSystem.FileSystem, path: Path.Path) {
description: metadata.description,
backend: metadata.backend,
repo: metadata.repo,
host: metadata.host,
};
}),
};
Expand Down
25 changes: 25 additions & 0 deletions packages/cli/src/backend/github/credentials.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,31 @@ describe("GithubCredentials", () => {
expect(result.message).toBe("run 'gh auth login', or set GH_TOKEN");
});

test("resolve reports the environment variable the token came from", async () => {
process.env.GITHUB_TOKEN = "github-token";
const credential = await runWithSpawner(
Effect.gen(function* () {
const credentials = yield* GithubCredentials;
return yield* credentials.resolve("github.com");
}),
() => Effect.fail(fakeSpawnFailure("should not be called")),
);
expect(credential.source).toBe("GITHUB_TOKEN");
expect(Redacted.value(credential.token)).toBe("github-token");
});

test("resolve reports `gh auth token` when it falls back to the CLI", async () => {
const credential = await runWithSpawner(
Effect.gen(function* () {
const credentials = yield* GithubCredentials;
return yield* credentials.resolve("github.com");
}),
() => Effect.succeed("cli-token\n"),
);
expect(credential.source).toBe("gh auth token");
expect(Redacted.value(credential.token)).toBe("cli-token");
});

test("never includes the resolved token in the missing-credentials error, even when other hosts had one cached", async () => {
const secret = "super-secret-token-value";
const result = await runWithSpawner(
Expand Down
42 changes: 32 additions & 10 deletions packages/cli/src/backend/github/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,23 @@ import { WayfulError } from "@domain/errors";

const MISSING_CREDENTIALS_MESSAGE = "run 'gh auth login', or set GH_TOKEN";

/** An environment variable the credential chain consults, in precedence order. */
export type GithubCredentialEnvVar = "WAYFUL_GITHUB_TOKEN" | "GH_TOKEN" | "GITHUB_TOKEN";

export const GITHUB_TOKEN_ENV_VARS: readonly GithubCredentialEnvVar[] = [
"WAYFUL_GITHUB_TOKEN",
"GH_TOKEN",
"GITHUB_TOKEN",
];

/** Where a resolved token came from, for `wayful doctor` to report. */
export type GithubCredentialSource = GithubCredentialEnvVar | "gh auth token";

export interface ResolvedCredential {
readonly token: Redacted.Redacted<string>;
readonly source: GithubCredentialSource;
}

const envToken = (name: string) =>
Config.option(Config.redacted(name))
.parse(ConfigProvider.fromEnv())
Expand All @@ -13,7 +30,11 @@ const envToken = (name: string) =>
export class GithubCredentials extends Context.Service<
GithubCredentials,
{
/** Resolves a bearer token for `host`; never reads `~/.config/gh/hosts.yml` directly. */
/**
* Resolves a bearer token for `host` alongside the place it came from;
* never reads `~/.config/gh/hosts.yml` directly.
*/
readonly resolve: (host: string) => Effect.Effect<ResolvedCredential, WayfulError>;
readonly token: (host: string) => Effect.Effect<Redacted.Redacted<string>, WayfulError>;
}
>()("wayful/GithubCredentials") {}
Expand Down Expand Up @@ -44,19 +65,20 @@ export const GithubCredentialsLayer = Layer.effect(
return resolved;
});

const token = (host: string) =>
const resolve = (host: string): Effect.Effect<ResolvedCredential, WayfulError> =>
Effect.gen(function* () {
const fromEnv = Option.firstSomeOf([
yield* envToken("WAYFUL_GITHUB_TOKEN"),
yield* envToken("GH_TOKEN"),
yield* envToken("GITHUB_TOKEN"),
]);
if (Option.isSome(fromEnv)) return fromEnv.value;
for (const name of GITHUB_TOKEN_ENV_VARS) {
const value = yield* envToken(name);
if (Option.isSome(value)) return { token: value.value, source: name };
}
const fromCli = yield* fromGhCli(host);
if (Option.isSome(fromCli)) return fromCli.value;
if (Option.isSome(fromCli)) return { token: fromCli.value, source: "gh auth token" };
return yield* new WayfulError({ message: MISSING_CREDENTIALS_MESSAGE });
});

return GithubCredentials.of({ token });
const token = (host: string) =>
resolve(host).pipe(Effect.map((credential) => credential.token));

return GithubCredentials.of({ resolve, token });
}),
);
87 changes: 87 additions & 0 deletions packages/cli/src/backend/github/doctor.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { describe, expect, test } from "bun:test";
import { Effect, Option } from "effect";

import { GithubCredentials } from "@backend/github/credentials";
import { diagnoseGithub } from "@backend/github/doctor";
import type { GithubHarnessOptions } from "@test/support/github/store";
import { runGithub } from "@test/support/github/store";
import { jsonResponse } from "@test/support/github/issues";
import type { ProjectHandle } from "@backend/ProjectStore";
import { WayfulError } from "@domain/errors";

function project(overrides: Partial<ProjectHandle> = {}): ProjectHandle {
return {
root: "/projects/wayful",
description: "",
backend: "github",
repo: "acme/widgets",
host: "github.example.com",
...overrides,
};
}

const permissionsResponse = jsonResponse(
200,
{ permissions: { push: true } },
{
"x-ratelimit-limit": "5000",
"x-ratelimit-remaining": "4999",
"x-ratelimit-reset": "1700000000",
"x-ratelimit-resource": "core",
},
);

describe("diagnoseGithub", () => {
test("resolves the repository, host, credential, labels, and rate limit", async () => {
let requested = "";
const diagnosis = await runGithub(
(request) => {
requested = request.url;
return permissionsResponse;
},
diagnoseGithub(project(), ["task", "research"]),
);
expect(requested).toBe("https://github.example.com/api/v3/repos/acme/widgets");
expect(diagnosis.repository).toBe("acme/widgets");
expect(diagnosis.host).toBe("github.example.com");
expect(diagnosis.credential).toBe("GH_TOKEN");
expect(diagnosis.labels).toEqual([
"wayful:map",
"wayful:step",
"wayful:goal",
"wayful:blocked",
"wayful:type/task",
"wayful:type/research",
]);
expect(Option.getOrThrow(diagnosis.rateLimit)).toEqual({
limit: 5000,
remaining: 4999,
reset: 1700000000,
resource: "core",
});
});

test("names an unusable credential as the problem", async () => {
const credentials: GithubCredentials["Service"] = {
resolve: () =>
Effect.fail(new WayfulError({ message: "run 'gh auth login', or set GH_TOKEN" })),
token: () =>
Effect.fail(new WayfulError({ message: "run 'gh auth login', or set GH_TOKEN" })),
};
const options: GithubHarnessOptions = { credentials };
const error = await runGithub(
() => jsonResponse(200, { permissions: { push: true } }),
diagnoseGithub(project(), []).pipe(Effect.flip),
options,
);
expect(error.message).toBe("github credential: run 'gh auth login', or set GH_TOKEN");
});

test("names the token when it cannot reach the repository", async () => {
const error = await runGithub(
() => jsonResponse(404, { message: "Not Found" }),
diagnoseGithub(project(), []).pipe(Effect.flip),
);
expect(error.message).toContain("github token cannot access acme/widgets");
});
});
Loading
Loading