Skip to content

test: Identifier ID generation and Protected.isSensitiveWrite edge cases#387

Closed
anandgupta42 wants to merge 2 commits intomainfrom
claude/test-id-protected-011oA4CKCyHc7Bv7MizQ5bh8
Closed

test: Identifier ID generation and Protected.isSensitiveWrite edge cases#387
anandgupta42 wants to merge 2 commits intomainfrom
claude/test-id-protected-011oA4CKCyHc7Bv7MizQ5bh8

Conversation

@anandgupta42
Copy link
Contributor

What does this PR do?

Adds first-ever unit tests for the Identifier module and expands edge-case coverage for Protected.isSensitiveWrite, filling two significant gaps discovered during automated test discovery.

1. Identifiersrc/id/id.ts (8 new tests)

This module generates every entity ID in the system (sessions, messages, tools, permissions, etc.) and its timestamp() function is used by Truncate.cleanup() to determine file age for retention. Zero tests existed prior to this PR. A bug in sort ordering would cause sessions/messages to display in wrong order; a bug in timestamp extraction would cause cleanup to delete recent output files or keep stale ones forever. New coverage includes:

  • Ascending and descending ID prefix correctness across multiple entity types
  • Chronological sort ordering for ascending IDs
  • Reverse-chronological sort ordering for descending IDs
  • timestamp() preserves ordering (used by Truncate.cleanup() for age comparison)
  • Idempotent passthrough when a valid ID is provided
  • Prefix mismatch throws an error
  • Monotonic counter differentiates same-millisecond IDs and maintains sort order

2. Protected.isSensitiveWrite edge cases — src/file/protected.ts (7 new tests)

This function gates whether the agent prompts the user before writing to sensitive files (credentials, private keys, config). The existing 6 tests covered .git, .ssh, .aws, .env, and credentials.json — but missed entire categories of sensitive patterns defined in the source. A user could write to server.pem, .docker/config.json, or .npmrc without any permission prompt. New coverage includes:

  • Private key and certificate extensions (.pem, .key, .p12, .pfx)
  • Remaining sensitive directories (.gnupg, .gcloud, .kube, .docker)
  • Remaining sensitive files (.npmrc, .pypirc, .netrc, .htpasswd, .pgpass, id_rsa, id_ed25519)
  • Sensitive files in nested subdirectories
  • Windows backslash path handling (split regex covers both separators)
  • .env.* variant detection via startsWith check with exact return values
  • False-positive resistance (files containing sensitive substrings like git-helper.ts are not flagged)

3. Fix: pre-existing typecheck errors in training-import.test.ts

The TrainingStore.count mock was missing context and rule keys (added in a recent TrainingKind expansion), and the fs.readFile mock had an overload type mismatch. These errors blocked the pre-push typecheck hook for all branches.

Type of change

  • New feature (non-breaking change which adds functionality)

Issue for this PR

N/A — proactive test coverage via automated test discovery

How did you verify your code works?

bun test test/id/id.test.ts                                          # 8 pass
bun test test/file/path-traversal.test.ts --test-name-pattern "private key|remaining sensitive dir|remaining sensitive file|subdirectories|Windows backslash|env variant|merely contain"  # 7 pass
bun run tsgo --noEmit                                                # 0 errors

Checklist

  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

https://claude.ai/code/session_011oA4CKCyHc7Bv7MizQ5bh8

claude added 2 commits March 23, 2026 00:11
Add first-ever tests for Identifier (monotonic ID generation, prefix validation,
sort ordering, timestamp extraction) and expand Protected.isSensitiveWrite coverage
for private key extensions, remaining sensitive dirs/files, and Windows paths.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

https://claude.ai/code/session_011oA4CKCyHc7Bv7MizQ5bh8
The mock for TrainingStore.count was missing `context` and `rule` keys,
and the fs.readFile mock had an overload mismatch. These errors blocked
the pre-push typecheck hook.

https://claude.ai/code/session_011oA4CKCyHc7Bv7MizQ5bh8
Copy link

@claude claude bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review to trigger a review.

Tip: disable this comment in your organization's Code Review settings.

@coderabbitai
Copy link

coderabbitai bot commented Mar 23, 2026

Warning

Rate limit exceeded

@anandgupta42 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 14 minutes and 7 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: c68583a0-93a1-4dbd-9966-53fed3c1c6d1

📥 Commits

Reviewing files that changed from the base of the PR and between d1e8419 and c7c399a.

📒 Files selected for processing (3)
  • packages/opencode/test/altimate/training-import.test.ts
  • packages/opencode/test/file/path-traversal.test.ts
  • packages/opencode/test/id/id.test.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/test-id-protected-011oA4CKCyHc7Bv7MizQ5bh8

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

anandgupta42 added a commit that referenced this pull request Mar 23, 2026
Merges 9 test PRs (#390, #394, #395, #396, #397, #398, #399, #401, #387)
into a single PR, discarding 4 duplicates (#391, #392, #393, #400).

**New test coverage:**
- `id.test.ts` — 14 tests: Identifier generation, monotonic ordering, timestamp extraction, Zod schema
- `shell.test.ts` — 9 tests: shell blacklist enforcement for fish/nu, cache reset, fallback
- `path-traversal.test.ts` — 7 tests (new): `Protected.isSensitiveWrite` for .pem/.key, .gnupg, .env variants
- `ignore.test.ts` — 7 tests (new): `FileIgnore.match` directory patterns, globs, whitelist overrides
- `paths-parsetext.test.ts` — 16 tests: `ConfigPaths.parseText` env/file substitution, JSONC parsing
- `finops-formatting.test.ts` — 14 tests: `formatBytes`/`truncateQuery` edge cases
- `finops-role-access.test.ts` — 10 tests: RBAC `formatGrants`/`formatHierarchy`/`formatUserRoles`
- `tool-lookup.test.ts` — 4 tests: Zod schema introspection for tool parameters
- `summary-git-path.test.ts` — 10 tests: `unquoteGitPath` decoding for non-ASCII filenames
- `tracing.test.ts` — 2 tests (added): Recap loop detection boundaries
- `patch.test.ts` — 9 tests (added): `maybeParseApplyPatchVerified` entry point coverage
- `instruction.test.ts` — 13 tests (new): `InstructionPrompt.loaded()` dedup guards
- `message-v2.test.ts` — 23 tests (new): `MessageV2.filterCompacted()` boundary detection

**Bug fixes (discovered during testing):**
- `finops-formatting.ts`: fix `formatBytes` crash on negative/NaN/fractional inputs
- `finops-formatting.ts`: fix `truncateQuery` returning empty for whitespace-only, exceeding `maxLen` when < 4
- `training-import.test.ts`: fix pre-existing typecheck errors (missing `context`/`rule` mock keys)
- `instruction.test.ts`, `message-v2.test.ts`: fix `MessageV2.Part` cast and branded ID type errors

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@anandgupta42
Copy link
Contributor Author

Consolidated into #403

@anandgupta42 anandgupta42 deleted the claude/test-id-protected-011oA4CKCyHc7Bv7MizQ5bh8 branch March 23, 2026 17:11
anandgupta42 added a commit that referenced this pull request Mar 23, 2026
* test: consolidated test coverage across 9 modules (133 new tests)

Merges 9 test PRs (#390, #394, #395, #396, #397, #398, #399, #401, #387)
into a single PR, discarding 4 duplicates (#391, #392, #393, #400).

**New test coverage:**
- `id.test.ts` — 14 tests: Identifier generation, monotonic ordering, timestamp extraction, Zod schema
- `shell.test.ts` — 9 tests: shell blacklist enforcement for fish/nu, cache reset, fallback
- `path-traversal.test.ts` — 7 tests (new): `Protected.isSensitiveWrite` for .pem/.key, .gnupg, .env variants
- `ignore.test.ts` — 7 tests (new): `FileIgnore.match` directory patterns, globs, whitelist overrides
- `paths-parsetext.test.ts` — 16 tests: `ConfigPaths.parseText` env/file substitution, JSONC parsing
- `finops-formatting.test.ts` — 14 tests: `formatBytes`/`truncateQuery` edge cases
- `finops-role-access.test.ts` — 10 tests: RBAC `formatGrants`/`formatHierarchy`/`formatUserRoles`
- `tool-lookup.test.ts` — 4 tests: Zod schema introspection for tool parameters
- `summary-git-path.test.ts` — 10 tests: `unquoteGitPath` decoding for non-ASCII filenames
- `tracing.test.ts` — 2 tests (added): Recap loop detection boundaries
- `patch.test.ts` — 9 tests (added): `maybeParseApplyPatchVerified` entry point coverage
- `instruction.test.ts` — 13 tests (new): `InstructionPrompt.loaded()` dedup guards
- `message-v2.test.ts` — 23 tests (new): `MessageV2.filterCompacted()` boundary detection

**Bug fixes (discovered during testing):**
- `finops-formatting.ts`: fix `formatBytes` crash on negative/NaN/fractional inputs
- `finops-formatting.ts`: fix `truncateQuery` returning empty for whitespace-only, exceeding `maxLen` when < 4
- `training-import.test.ts`: fix pre-existing typecheck errors (missing `context`/`rule` mock keys)
- `instruction.test.ts`, `message-v2.test.ts`: fix `MessageV2.Part` cast and branded ID type errors

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address code review findings — test artifact leakage and cleanup

- summary-git-path.test.ts: use tmpdir() instead of projectRoot to prevent
  Storage.write() from polluting the developer's .opencode/storage/ directory
- finops-role-access.test.ts: consolidate duplicate afterAll hooks to ensure
  ALTIMATE_TELEMETRY_DISABLED env var is cleaned up after tests

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants