Skip to content

feat(auth): implement human authentication and session lifecycle (#163) - #177

Merged
KalebCole merged 14 commits into
mainfrom
feat/163-auth-session
Aug 11, 2026
Merged

KalebCole merged 14 commits into
mainfrom
feat/163-auth-session

Conversation

@KalebCole

@KalebCole KalebCole commented Aug 11, 2026 •

Copy link
Copy Markdown
Owner

Summary

Implements the complete S2 authentication lifecycle and closes #163 against owner-reviewed Remote API contract revision 2026-08-11.4.

  • Adds private-terminal-only auth login, redacted status, and serialized logout.
  • Implements exact reviewed callable and Firebase mappings; Firebase uses the public key query parameter and required Referer, never Origin, while callable requests add no uncontracted browser headers.
  • Refreshes within five minutes of expiry and atomically replaces credentials under a cross-process lock on Linux, macOS, and Windows.
  • Keeps auth and remote separately substitutable: internal/auth owns the port and lifecycle vocabulary; internal/remote is the checked wire adapter.
  • Declares executable parser/auth failures and accurate local-mutation safety through schema.
  • Bounds every auth response to 64 KiB, validates declared field types, permits reviewed additional properties, and fails drift closed.

Slice boundary

The first protected-command auth.required tracer and session acquisition materialize in #164 with the first evidence-complete protected event command. The stable private account fingerprint materializes in #166 with its first mutation-plan consumer.

Safety and validation

No live authentication, SMS, credential entry, browser login, live probe, or Partiful mutation was used. Phone numbers, codes, tokens, identity values, remote bodies, and filesystem details never enter stdout/stderr.

Go race/vet/build/module checks, Linux/macOS/Windows target builds, 20 contract tests plus drift tests, 341 non-live JavaScript tests, typecheck, formatting/diff/privacy guards, and independent Standards/Spec review all pass.

Closes #163

Summary by CodeRabbit

  • New Features

    • Added the auth.login command for interactive authentication.
    • Added automatic credential refresh for near-expiry sessions.
    • Added secure credential storage with atomic updates and logout safeguards.
    • Added support for terminal validation and unavailable-terminal detection.
  • Bug Fixes

    • Improved authentication error reporting for expired credentials, rejected codes, unavailable services, and invalid responses.
    • Added response-size and protocol validation to fail safely on malformed authentication responses.
  • Documentation

    • Updated the CLI contract and authentication behavior documentation.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 4c36f0b1-daeb-45a7-965c-97b4866e5d58

📥 Commits

Reviewing files that changed from the base of the PR and between 8677e9e and 7aac3eb.

📒 Files selected for processing (5)
  • docs/CLI-PRODUCT-CONTRACT.md
  • internal/app/execute_test.go
  • internal/auth/auth.go
  • internal/auth/os_terminal.go
  • internal/remote/auth.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/auth/os_terminal.go
  • internal/auth/auth.go
  • internal/remote/auth.go
  • docs/CLI-PRODUCT-CONTRACT.md

📝 Walkthrough

Walkthrough

The CLI adds interactive authentication login, remote token exchange and refresh, atomic credential persistence, terminal secret input, expanded authentication error mappings, and updated contract schemas and tests.

Changes

Authentication lifecycle

Layer / File(s) Summary
Remote authentication contract
internal/auth/port.go, internal/remote/auth.go, go.mod
Defines authentication requests and responses. Implements code delivery, token exchange, Firebase sign-in, refresh, response validation, and a 64 KiB response limit.
Credential storage and session state
internal/auth/auth.go, internal/auth/persist.go, internal/auth/os_*.go
Adds refresh-token storage, token-state handling, filesystem locking, atomic writes, and platform-specific file operations.
Terminal and CLI authentication integration
cmd/partiful/main.go, internal/app/app.go, internal/auth/os_terminal.go, internal/auth/os_terminal_signals_*.go
Registers auth.login, injects terminal and randomness dependencies, performs login and refresh, reads terminal secrets, and maps authentication failures.
Contract documentation and validation
docs/CLI-PRODUCT-CONTRACT.md, internal/app/execute_test.go
Updates the contract revision and schema rules. Tests login, refresh, persistence, concurrency, redaction, protocol validation, status mappings, and command metadata.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant OSTerminal
  participant AuthLogin
  participant AuthClient
  participant CredentialStore
  CLI->>OSTerminal: read authentication secret
  CLI->>AuthLogin: execute login
  AuthLogin->>AuthClient: exchange authentication data
  AuthClient-->>AuthLogin: return tokens
  AuthLogin->>CredentialStore: atomically save credentials
  CredentialStore-->>CLI: return authentication state
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main change: human authentication and session lifecycle support.
Linked Issues check ✅ Passed The changes implement the authentication commands, terminal restrictions, refresh flow, atomic persistence, remote mappings, and redaction required by issue #163.
Out of Scope Changes check ✅ Passed The code, contract documentation, dependencies, platform helpers, and tests all directly support the authentication and session-lifecycle objectives.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/163-auth-session

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.

@github-actions

github-actions Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
PR Preview Action v1.8.1
Preview removed because the pull request was closed.
2026-08-11 21:02 UTC

KalebCole added a commit that referenced this pull request Aug 11, 2026
…178)

* docs(contract): formalize Firebase transport configuration

Propose remote contract revision 2026-08-11.3 adding two transport
configuration facts absent from 2026-08-11.2 that the Go implementation
(PR #177) requires for signInWithCustomToken, refreshToken, and
lookupFirebaseUser:

1. Firebase web API key value: the firebaseApiKey security scheme now
   carries x-publicValue with the observed public key. This is embedded
   in every Partiful web client and documented in the March 24, 2026
   browser interception. It is not a credential.

2. Referer header requirement: each Firebase operation now has a required
   Referer: https://partiful.com/ header parameter. Documented in the
   August 11, 2026 auth observation. Requests without it receive 403
   API_KEY_HTTP_REFERRER_BLOCKED.

Origin is NOT modelled. Agent probes succeeded without Origin, receiving
valid 400 error responses. Origin is browser CORS behavior, not a
Firebase transport requirement.

Material claims: 992 -> 1008
Contract revision: 2026-08-11.3 (proposed, pending owner approval)
Pacific full suite: 338 passed, 6 skipped, 0 failed

Linked to #163

Co-authored-by: Copilot <[email protected]>

* docs(contract): clarify observed Referer boundary

Describe the observed accepted Referer separately from the unknown complete allowlist so revision 2026-08-11.3 does not overstate remote behavior.

Co-authored-by: Copilot <[email protected]>

* fix(contract): sanitize Firebase evidence provenance (#163)

Co-authored-by: Copilot <[email protected]>

Copilot-Session: 8453c76f-a887-4fce-be42-d7997ed94292

* fix(contract): isolate public auth provenance

Move the public Firebase configuration claim to a dedicated privacy-safe evidence extract, reject unsafe provenance, and keep Origin unmodelled and unknown.

Co-authored-by: Copilot <[email protected]>

* test(contract): guard sanitized auth evidence

Require redacted identity fields, retain public transport structure, and reject private-value patterns in the tracked historical auth note.

Co-authored-by: Copilot <[email protected]>

* docs(contract): normalize Firebase evidence formatting (#163)

Co-authored-by: Copilot <[email protected]>

Copilot-Session: 8453c76f-a887-4fce-be42-d7997ed94292

* fix(contract): correct auth request provenance

Keep all authentication request schemas TypeScript-derived while preserving dated observation classifications for responses and the separately observed Firebase transport facts.

Co-authored-by: Copilot <[email protected]>

* docs(contract): approve Firebase transport revision (#163)

Co-authored-by: Copilot <[email protected]>

Copilot-Session: 8453c76f-a887-4fce-be42-d7997ed94292

---------

Co-authored-by: Ubuntu <azureuser@vm-copilot-agent.orgktuxli0vefjkhtvkzmrvmvh.xx.internal.cloudapp.net>
Co-authored-by: Copilot <[email protected]>
Copilot-Session: 8453c76f-a887-4fce-be42-d7997ed94292
Ubuntu and others added 10 commits August 11, 2026 16:53
Implement the reviewed callable and Firebase exchange flow, atomic credential persistence, redacted failure mappings, and auth.login schema registration.

Co-authored-by: Copilot <[email protected]>
Refresh expiring credentials once through the reviewed token mapping, persist rotations atomically, fail closed on drift, and add definition-driven protected-session guards without prompting.

Co-authored-by: Copilot <[email protected]>
Reject refresh and sign-in lifetimes that cannot be represented safely, and keep protected-session credential corruption on the redacted local failure path.

Co-authored-by: Copilot <[email protected]>
1. Update RemoteContractRevision from 2026-08-11.2 to 2026-08-11.3 and
   all test expectations to match.

2. Remove Origin header from Firebase auth requests (signInWithCustomToken,
   refreshToken). Origin is not modelled in the approved contract — agent
   probes confirmed Firebase accepts requests without it. Keep Referer
   exactly as contracted.

3. Add end-to-end test assertions verifying Firebase requests send the
   contracted Referer header and do NOT send Origin. Callable requests
   retain Origin per browser-interception evidence.

4. Public Firebase web key stays confined to internal/remote/auth.go only;
   no key/credential/private values enter output or diagnostics.

Pacific full suite: 341 passed, 6 skipped, 0 failed
Cross-platform builds: linux/amd64, darwin/arm64, windows/amd64

Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>

Copilot-Session: 7b842425-e150-41a6-9cd2-6b0842fe8c01
Co-authored-by: Copilot <[email protected]>

Copilot-Session: 7b842425-e150-41a6-9cd2-6b0842fe8c01
Co-authored-by: Copilot <[email protected]>

Copilot-Session: 7b842425-e150-41a6-9cd2-6b0842fe8c01
Co-authored-by: Copilot <[email protected]>

Copilot-Session: 7b842425-e150-41a6-9cd2-6b0842fe8c01
Co-authored-by: Copilot <[email protected]>

Copilot-Session: 7b842425-e150-41a6-9cd2-6b0842fe8c01
Co-authored-by: Copilot <[email protected]>

Copilot-Session: 7b842425-e150-41a6-9cd2-6b0842fe8c01
@KalebCole
KalebCole force-pushed the feat/163-auth-session branch from 4fd079a to 112fc57 Compare August 11, 2026 18:19

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 7

🧹 Nitpick comments (7)
internal/auth/auth.go (1)

206-216: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the redundant credentialRecord copy.

Lines 207-211 build the refreshed record and assign it to credentials. Lines 212-216 then build a second, field-for-field identical record and pass that to saveCredentialsUnlocked. Pass credentials directly.

♻️ Proposed refactor
 		expiresAt := now.Add(refreshed.ExpiresIn).UTC()
 		credentials = credentialRecord{
 			AccessToken:  refreshed.IDToken,
 			RefreshToken: refreshed.RefreshToken,
 			ExpiresAt:    expiresAt,
 		}
-		operationErr = saveCredentialsUnlocked(files, path, credentialRecord{
-			AccessToken:  credentials.AccessToken,
-			RefreshToken: credentials.RefreshToken,
-			ExpiresAt:    credentials.ExpiresAt,
-		})
+		operationErr = saveCredentialsUnlocked(files, path, credentials)
 		if operationErr != nil {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/auth/auth.go` around lines 206 - 216, Remove the redundant
credentialRecord reconstruction in the refresh flow: after assigning the
refreshed values to credentials, pass credentials directly to
saveCredentialsUnlocked. Preserve the existing save behavior and error handling.
internal/auth/os_unix.go (1)

32-34: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the dead conditional in syncDirectory.

syncDirectory returns no value. The return at line 33 is the last statement of the function, so the condition and its body have no effect. The errors.Is(err, fs.ErrInvalid) test also has no effect.

The code reads as if it distinguishes a tolerated fs.ErrInvalid from a real failure. It does not. Collapse it to an explicit discard so the intent matches the behavior.

♻️ Proposed refactor
 func syncDirectory(directory string) {
 	handle, err := os.Open(directory)
 	if err != nil {
 		return
 	}
 	defer handle.Close()
-	if err := handle.Sync(); err != nil && !errors.Is(err, fs.ErrInvalid) {
-		return
-	}
+	// Some filesystems reject fsync on a directory. A durability best effort is sufficient here.
+	_ = handle.Sync()
 }

This removes the only uses of errors and io/fs, so drop both imports.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/auth/os_unix.go` around lines 32 - 34, In syncDirectory, replace the
final conditional Sync error check with an explicit discard of handle.Sync’s
result, since the function returns immediately either way. Remove the now-unused
errors and io/fs imports.
internal/auth/persist.go (1)

18-24: 🔒 Security & Privacy | 🔵 Trivial | 💤 Low value

Consider mapping the WriteFileAtomic error to ErrPersistence here.

Line 23 returns the raw filesystem error. That error can contain the credential file path. Both current callers replace it with ErrPersistence (internal/auth/auth.go lines 121-123 and lines 217-219), so no filesystem detail reaches the output today.

The product contract requires that filesystem errors stay out of the output. Mapping the error at the source makes that guarantee hold for any future caller.

♻️ Proposed hardening
 func saveCredentialsUnlocked(files FileSystem, path string, credentials credentialRecord) error {
 	document, err := json.Marshal(credentials)
 	if err != nil {
 		return ErrUnavailable
 	}
-	return files.WriteFileAtomic(path, document)
+	if err := files.WriteFileAtomic(path, document); err != nil {
+		return ErrPersistence
+	}
+	return nil
 }

internal/auth/auth.go line 218 then reassigns ErrPersistence to itself, which stays correct.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/auth/persist.go` around lines 18 - 24, Update
saveCredentialsUnlocked so errors returned by files.WriteFileAtomic are mapped
to ErrPersistence instead of being returned directly, while preserving the
existing ErrUnavailable mapping for json.Marshal failures.
internal/remote/auth.go (2)

104-118: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename the local variable url to avoid shadowing the net/url package.

Line 112 declares a local variable named url. The file imports net/url and uses url.Values in RefreshToken. The code compiles today because SignInWithCustomToken does not use the package. A later edit that needs url.Values in this function will fail to compile. callablePost uses the same parameter name at line 239.

♻️ Proposed rename
-	url := firebaseIdentityHost + "/v1/accounts:signInWithCustomToken?key=" + firebaseProjectKey
-	request, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
+	endpoint := firebaseIdentityHost + "/v1/accounts:signInWithCustomToken?key=" + firebaseProjectKey
+	request, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload))
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/remote/auth.go` around lines 104 - 118, Rename the local `url`
variable in `AuthClient.SignInWithCustomToken` to a non-conflicting name and
update the `http.NewRequestWithContext` call to use it. Also rename the
corresponding `url` parameter in `callablePost` to avoid shadowing the imported
`net/url` package there.

227-237: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Simplify parseExpiresIn and keep the overflow guard explicit.

The function parses an integer, formats it back to a string, and then calls time.ParseDuration. The round trip exists only because time.ParseDuration rejects values that overflow time.Duration. An explicit bound expresses that intent directly and removes the string round trip.

time.Duration is an int64 nanosecond count, so the maximum representable value is about 292 years.

♻️ Proposed refactor
 func parseExpiresIn(value string) (time.Duration, error) {
 	seconds, err := strconv.ParseInt(value, 10, 64)
 	if err != nil || seconds <= 0 {
 		return 0, auth.ErrRemoteProtocolChanged
 	}
-	duration, err := time.ParseDuration(strconv.FormatInt(seconds, 10) + "s")
-	if err != nil {
+	if seconds > int64(math.MaxInt64/time.Second) {
 		return 0, auth.ErrRemoteProtocolChanged
 	}
-	return duration, nil
+	return time.Duration(seconds) * time.Second, nil
 }

Add "math" to the import block.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/remote/auth.go` around lines 227 - 237, Update parseExpiresIn to
remove the strconv.FormatInt/time.ParseDuration round trip and explicitly reject
seconds above the maximum representable time.Duration in seconds, using
math.MaxInt64 and the existing nonpositive validation. Return the same
auth.ErrRemoteProtocolChanged error for invalid or overflowing values, and
construct the duration directly from seconds.
internal/app/execute_test.go (2)

1488-1515: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Extract the repeated login dependency scaffold into a helper.

Nine login tests repeat the same app.Dependencies literal: memoryFilesystem, the fixed credentials path, a scripted terminal, AuthRandom, and the same fixed Now. Only the HTTP script differs. A helper reduces the duplication and keeps the fixed clock consistent when it changes.

♻️ Proposed helper
func loginDependencies(http remote.HTTPClient, values ...string) app.Dependencies {
	return app.Dependencies{
		Files:           &memoryFilesystem{files: map[string][]byte{}},
		CredentialsPath: "/config/partiful/credentials.json",
		Terminal:        &scriptedPrivateTerminal{values: values},
		AuthRandom:      strings.NewReader("0123456789abcdef"),
		Now: func() time.Time {
			return time.Date(2026, time.August, 11, 0, 0, 0, 0, time.UTC)
		},
		HTTP: http,
	}
}

Tests that inspect the terminal or the filesystem can still build the struct and override the field.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/app/execute_test.go` around lines 1488 - 1515, Extract the repeated
login dependency setup into a loginDependencies helper accepting the HTTP client
and terminal values, including the shared filesystem, credentials path,
AuthRandom, and fixed Now configuration. Update the nine login tests to use this
helper while preserving their individual HTTP scripts; tests that inspect or
customize terminal/filesystem dependencies may construct and override those
fields as needed.

1517-1544: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Set Content-Type: application/json on the oversized response.

The current test fails at media-type validation before readBoundedAuthBody reads the body. Add the header so the body length proves the size limit.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/app/execute_test.go` around lines 1517 - 1544, Update the HTTP
response returned by the scriptedHTTP callback in
TestExecuteAuthLoginRejectsOversizedSendAcknowledgement to include Content-Type:
application/json, ensuring media-type validation passes and the oversized body
reaches readBoundedAuthBody.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/CLI-PRODUCT-CONTRACT.md`:
- Around line 285-293: Update the auth status behavior description around token
refresh to explicitly state that already expired stored credentials with a
refresh token are also refreshed. Preserve the existing outcomes for credentials
without a refresh token and the documented refresh/error behavior.

In `@internal/app/app.go`:
- Around line 890-904: Update the contract schema example around the documented
failureTypes field to reflect that every command includes the default
usage.invalid and input.invalid failures, or explicitly mark the empty array as
illustrative. Keep the example consistent with declaredFailureTypes and the
existing schema-test expectations.

In `@internal/app/execute_test.go`:
- Around line 1624-1658: Update
TestExecuteAuthLoginAllowsUndeclaredFirebaseErrorField to use a string status
value or omit the status field so validFirebaseTokenError accepts the fixture
and the test produces INVALID_CUSTOM_TOKEN. Rename the test to describe the
actual optional Firebase error field and intended behavior.

In `@internal/auth/auth.go`:
- Line 82: Update Login and refreshCredentials to use an injected clock function
rather than the fixed login-start time: read the current time immediately after
the sign-in response and use it for sessionID and expiresAt calculations.
Preserve deterministic tests by using the existing Now injection with a constant
implementation.

In `@internal/auth/os_terminal.go`:
- Around line 25-29: Update the command-level flow around both ReadSecret calls
to install SIGINT/SIGTERM handling that restores terminal echo before preserving
the signals’ normal process termination behavior. Ensure cleanup covers
interruptions during either term.ReadPassword invocation and does not alter
successful credential input handling.

In `@internal/auth/os_windows.go`:
- Around line 28-42: Update the credential storage flow using
DefaultCredentialsPath to enforce a user-only Windows DACL when creating the
parent directory and temporary credentials file, rather than relying on MkdirAll
or Chmod permissions. Ensure files remain inaccessible to other users even when
AppData is shared; alternatively, reject shared AppData locations before writing
credentials. Use the existing credential creation helpers and replaceFile flow
without changing unrelated file replacement behavior.

In `@internal/remote/auth.go`:
- Line 52: Make all six deferred Close calls explicitly discard their errors to
satisfy errcheck: update SendAuthCode, GetLoginToken, SignInWithCustomToken, and
RefreshToken in internal/remote/auth.go; WithLock in internal/auth/os_files.go,
preserving release() before closing; and syncDirectory in
internal/auth/os_unix.go. Wrap each Close in a deferred function assigning the
result to _, without changing other behavior.

---

Nitpick comments:
In `@internal/app/execute_test.go`:
- Around line 1488-1515: Extract the repeated login dependency setup into a
loginDependencies helper accepting the HTTP client and terminal values,
including the shared filesystem, credentials path, AuthRandom, and fixed Now
configuration. Update the nine login tests to use this helper while preserving
their individual HTTP scripts; tests that inspect or customize
terminal/filesystem dependencies may construct and override those fields as
needed.
- Around line 1517-1544: Update the HTTP response returned by the scriptedHTTP
callback in TestExecuteAuthLoginRejectsOversizedSendAcknowledgement to include
Content-Type: application/json, ensuring media-type validation passes and the
oversized body reaches readBoundedAuthBody.

In `@internal/auth/auth.go`:
- Around line 206-216: Remove the redundant credentialRecord reconstruction in
the refresh flow: after assigning the refreshed values to credentials, pass
credentials directly to saveCredentialsUnlocked. Preserve the existing save
behavior and error handling.

In `@internal/auth/os_unix.go`:
- Around line 32-34: In syncDirectory, replace the final conditional Sync error
check with an explicit discard of handle.Sync’s result, since the function
returns immediately either way. Remove the now-unused errors and io/fs imports.

In `@internal/auth/persist.go`:
- Around line 18-24: Update saveCredentialsUnlocked so errors returned by
files.WriteFileAtomic are mapped to ErrPersistence instead of being returned
directly, while preserving the existing ErrUnavailable mapping for json.Marshal
failures.

In `@internal/remote/auth.go`:
- Around line 104-118: Rename the local `url` variable in
`AuthClient.SignInWithCustomToken` to a non-conflicting name and update the
`http.NewRequestWithContext` call to use it. Also rename the corresponding `url`
parameter in `callablePost` to avoid shadowing the imported `net/url` package
there.
- Around line 227-237: Update parseExpiresIn to remove the
strconv.FormatInt/time.ParseDuration round trip and explicitly reject seconds
above the maximum representable time.Duration in seconds, using math.MaxInt64
and the existing nonpositive validation. Return the same
auth.ErrRemoteProtocolChanged error for invalid or overflowing values, and
construct the duration directly from seconds.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: c3a98ce4-9b25-489b-bf36-77e18675187f

📥 Commits

Reviewing files that changed from the base of the PR and between b2a55e6 and 112fc57.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (13)
  • cmd/partiful/main.go
  • docs/CLI-PRODUCT-CONTRACT.md
  • go.mod
  • internal/app/app.go
  • internal/app/execute_test.go
  • internal/auth/auth.go
  • internal/auth/os_files.go
  • internal/auth/os_terminal.go
  • internal/auth/os_unix.go
  • internal/auth/os_windows.go
  • internal/auth/persist.go
  • internal/auth/port.go
  • internal/remote/auth.go

Comment thread docs/CLI-PRODUCT-CONTRACT.md Resolved
Comment thread internal/app/app.go Resolved
Comment thread internal/app/execute_test.go Outdated
Comment on lines +1624 to +1658
func TestExecuteAuthLoginAllowsUndeclaredFirebaseErrorField(t *testing.T) {
call := 0
result := app.Execute(context.Background(), app.Request{
Argv: []string{"auth", "login"},
}, app.Dependencies{
Files: &memoryFilesystem{files: map[string][]byte{}},
CredentialsPath: "/config/partiful/credentials.json",
Terminal: &scriptedPrivateTerminal{values: []string{"+15555550123", "123456"}},
AuthRandom: strings.NewReader("0123456789abcdef"),
Now: func() time.Time {
return time.Date(2026, time.August, 11, 0, 0, 0, 0, time.UTC)
},
HTTP: scriptedHTTP{do: func(*http.Request) (*http.Response, error) {
call++
switch call {
case 1:
return jsonResponse(http.StatusOK, `{}`), nil
case 2:
return jsonResponse(
http.StatusOK,
`{"result":{"data":{"token":"custom-private-token"}}}`,
), nil
default:
return jsonResponse(
http.StatusBadRequest,
`{"error":{"code":400,"message":"invalid token","status":123}}`,
), nil
}
}},
})
if result.ExitCode != 3 ||
!strings.Contains(result.Stdout, `"code":"INVALID_CUSTOM_TOKEN"`) {
t.Fatalf("result = %#v, want undeclared Firebase error field to remain allowed", result)
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Inspect Firebase token-error validation and the declared optional fields.
set -euo pipefail

rg -n -C15 'func validFirebaseTokenError|func validCallableAuthError|func validOptionalString' internal/remote

Repository: KalebCole/partiful-cli

Length of output: 5056


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- validator and callers ---'
sed -n '288,386p' internal/remote/auth.go
rg -n -C12 'validFirebaseTokenError|TestExecuteAuthLoginAllowsUndeclaredFirebaseErrorField|TestExecuteAuthStatusMapsReviewedInvalidRefreshTokenToExpired|INVALID_CUSTOM_TOKEN' internal

printf '%s\n' '--- exact test region ---'
sed -n '1600,1680p' internal/app/execute_test.go
sed -n '2200,2260p' internal/app/execute_test.go

Repository: KalebCole/partiful-cli

Length of output: 20169


🏁 Script executed:

#!/bin/bash
set -euo pipefail

if ! command -v go >/dev/null 2>&1; then
  echo "go unavailable"
  exit 0
fi

cat >/tmp/check_firebase_status.go <<'EOF'
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
)

func validOptionalString(raw json.RawMessage) bool {
	if len(raw) == 0 {
		return true
	}
	if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
		return false
	}
	var value string
	return json.Unmarshal(raw, &value) == nil
}

func validFirebaseTokenError(data []byte) bool {
	var failure struct {
		Error *struct {
			Code    *float64        `json:"code"`
			Message *string         `json:"message"`
			Status  json.RawMessage `json:"status"`
		} `json:"error"`
	}
	return json.Unmarshal(data, &failure) == nil &&
		failure.Error != nil &&
		failure.Error.Code != nil &&
		failure.Error.Message != nil &&
		validOptionalString(failure.Error.Status)
}

func main() {
	for _, body := range []string{
		`{"error":{"code":400,"message":"invalid token","status":123}}`,
		`{"error":{"code":400,"message":"invalid token","status":"INVALID_ARGUMENT"}}`,
		`{"error":{"code":400,"message":"invalid token"}}`,
	} {
		fmt.Printf("%s => %t\n", body, validFirebaseTokenError([]byte(body)))
	}
}
EOF

go run /tmp/check_firebase_status.go
rm -f /tmp/check_firebase_status.go

Repository: KalebCole/partiful-cli

Length of output: 373


Use a string or omit status in this test.

validFirebaseTokenError rejects numeric status values. The current fixture produces AUTH_PROTOCOL_CHANGED, not INVALID_CUSTOM_TOKEN. Rename the test to describe the actual optional field and intent.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/app/execute_test.go` around lines 1624 - 1658, Update
TestExecuteAuthLoginAllowsUndeclaredFirebaseErrorField to use a string status
value or omit the status field so validFirebaseTokenError accepts the fixture
and the test produces INVALID_CUSTOM_TOKEN. Rename the test to describe the
actual optional Firebase error field and intended behavior.

Comment thread internal/auth/auth.go Resolved
Comment thread internal/auth/os_terminal.go Resolved
Comment thread internal/auth/os_windows.go Resolved
Comment thread internal/remote/auth.go Resolved
Co-authored-by: Copilot <[email protected]>

Copilot-Session: 7b842425-e150-41a6-9cd2-6b0842fe8c01

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/auth/os_terminal.go`:
- Around line 35-37: Update the error handling around readRawSecret to preserve
and return ErrInputInvalid unchanged when the 4 KiB input limit is reached,
while continuing to map other read failures to ErrUnavailable so auth.Login
exposes the documented validation error.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 109563d3-8b8d-427d-98d0-53f28a6146d2

📥 Commits

Reviewing files that changed from the base of the PR and between 112fc57 and 8677e9e.

📒 Files selected for processing (12)
  • docs/CLI-PRODUCT-CONTRACT.md
  • internal/app/app.go
  • internal/app/execute_test.go
  • internal/auth/auth.go
  • internal/auth/os_files.go
  • internal/auth/os_terminal.go
  • internal/auth/os_terminal_signals_unix.go
  • internal/auth/os_terminal_signals_windows.go
  • internal/auth/os_unix.go
  • internal/auth/os_windows.go
  • internal/auth/persist.go
  • internal/remote/auth.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/auth/persist.go
  • internal/remote/auth.go
  • internal/app/app.go
  • internal/auth/os_files.go

Comment thread internal/auth/os_terminal.go Resolved
Ubuntu added 3 commits August 11, 2026 19:55
Co-authored-by: Copilot <[email protected]>

Copilot-Session: 7b842425-e150-41a6-9cd2-6b0842fe8c01
Co-authored-by: Copilot <[email protected]>

Copilot-Session: 7b842425-e150-41a6-9cd2-6b0842fe8c01
Co-authored-by: Copilot <[email protected]>

Copilot-Session: 7b842425-e150-41a6-9cd2-6b0842fe8c01
@KalebCole
KalebCole merged commit 162cbe5 into main Aug 11, 2026
2 checks passed
@KalebCole
KalebCole deleted the feat/163-auth-session branch August 11, 2026 21:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement human authentication and session lifecycle in Go

1 participant