-
Notifications
You must be signed in to change notification settings - Fork 7
feat(observe): surface revoked install tokens; doctor managed-observe section #278
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
michiosw
wants to merge
1
commit into
selfserve-setup-command
Choose a base branch
from
selfserve-auth-devx
base: selfserve-setup-command
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| package managedobserve | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "errors" | ||
| "io/fs" | ||
| "os" | ||
| "path/filepath" | ||
| "time" | ||
| ) | ||
|
|
||
| // AuthError is the on-disk breadcrumb a daemon leaves when it cannot | ||
| // authenticate: kind "auth" for hosted-ledger rejections (revoked token), | ||
| // kind "startup" when the install token could not even be resolved (locked | ||
| // keychain, missing item). The daemon's stderr goes to a log file nobody | ||
| // watches, so `kontext doctor` reads this file to give the user the actual | ||
| // next step. | ||
| type AuthError struct { | ||
| Kind string `json:"kind"` | ||
| Status int `json:"status,omitempty"` | ||
| Message string `json:"message,omitempty"` | ||
| At string `json:"at"` | ||
| } | ||
|
|
||
| const authErrorKindCorrupt = "corrupt" | ||
|
|
||
| // AuthErrorPath puts the breadcrumb next to the observe database — the one | ||
| // directory both the daemon and doctor can always derive. | ||
| func AuthErrorPath(dbPath string) string { | ||
| return filepath.Join(filepath.Dir(dbPath), "last-auth-error.json") | ||
| } | ||
|
|
||
| func WriteAuthError(dbPath string, status int) error { | ||
| return writeBreadcrumb(dbPath, AuthError{Kind: "auth", Status: status}) | ||
| } | ||
|
|
||
| // WriteStartupError records that the daemon exited before streaming — e.g. | ||
| // the keychain item was unreadable under launchd. Without it, doctor can only | ||
| // say "daemon: not running" with no cause. | ||
| func WriteStartupError(dbPath string, message string) error { | ||
| return writeBreadcrumb(dbPath, AuthError{Kind: "startup", Message: message}) | ||
| } | ||
|
|
||
| func writeBreadcrumb(dbPath string, breadcrumb AuthError) error { | ||
| breadcrumb.At = time.Now().UTC().Format(time.RFC3339) | ||
| data, err := json.Marshal(breadcrumb) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if err := os.MkdirAll(filepath.Dir(AuthErrorPath(dbPath)), 0o755); err != nil { | ||
| return err | ||
| } | ||
| return os.WriteFile(AuthErrorPath(dbPath), append(data, '\n'), 0o600) | ||
| } | ||
|
|
||
| func ClearAuthError(dbPath string) { | ||
| _ = os.Remove(AuthErrorPath(dbPath)) | ||
| } | ||
|
|
||
| // LoadAuthError returns the breadcrumb, or nil when none exists. Unreadable or | ||
| // corrupt files are returned as a distinct diagnostic kind so doctor never | ||
| // turns a local breadcrumb problem into a false revoked-token warning. | ||
| func LoadAuthError(dbPath string) *AuthError { | ||
| data, err := os.ReadFile(AuthErrorPath(dbPath)) | ||
| if err != nil { | ||
| if !errors.Is(err, fs.ErrNotExist) { | ||
| return &AuthError{Kind: authErrorKindCorrupt, Message: err.Error()} | ||
| } | ||
| return nil | ||
| } | ||
| var authErr AuthError | ||
| if err := json.Unmarshal(data, &authErr); err != nil { | ||
| return &AuthError{Kind: authErrorKindCorrupt, Message: err.Error()} | ||
| } | ||
| return &authErr | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| package managedobserve | ||
|
|
||
| import ( | ||
| "net/http" | ||
| "os" | ||
| "path/filepath" | ||
| "testing" | ||
| ) | ||
|
|
||
| func TestAuthErrorRoundTrip(t *testing.T) { | ||
| dbPath := filepath.Join(t.TempDir(), "guard.db") | ||
|
|
||
| if got := LoadAuthError(dbPath); got != nil { | ||
| t.Fatalf("LoadAuthError before write = %v, want nil", got) | ||
| } | ||
|
|
||
| if err := WriteAuthError(dbPath, http.StatusUnauthorized); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| got := LoadAuthError(dbPath) | ||
| if got == nil || got.Status != http.StatusUnauthorized || got.Kind != "auth" || got.At == "" { | ||
| t.Fatalf("LoadAuthError = %+v", got) | ||
| } | ||
|
|
||
| ClearAuthError(dbPath) | ||
| if got := LoadAuthError(dbPath); got != nil { | ||
| t.Fatalf("LoadAuthError after clear = %v, want nil", got) | ||
| } | ||
| // Clearing again is a no-op. | ||
| ClearAuthError(dbPath) | ||
| } | ||
|
|
||
| func TestStartupErrorRoundTrip(t *testing.T) { | ||
| dbPath := filepath.Join(t.TempDir(), "nested", "guard.db") // dir created on demand | ||
|
|
||
| if err := WriteStartupError(dbPath, "resolve install token: keychain locked"); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| got := LoadAuthError(dbPath) | ||
| if got == nil || got.Kind != "startup" || got.Message == "" || got.At == "" { | ||
| t.Fatalf("LoadAuthError = %+v", got) | ||
| } | ||
|
|
||
| ClearAuthError(dbPath) | ||
| if LoadAuthError(dbPath) != nil { | ||
| t.Fatal("startup breadcrumb not cleared") | ||
| } | ||
| } | ||
|
|
||
| func TestLoadAuthErrorToleratesCorruptBreadcrumb(t *testing.T) { | ||
| dbPath := filepath.Join(t.TempDir(), "guard.db") | ||
| if err := os.WriteFile(AuthErrorPath(dbPath), []byte("{corrupt"), 0o600); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| // Doctor reporting must never fail on a corrupt file, and must not turn a | ||
| // local breadcrumb problem into a false revoked-token warning. | ||
| if got := LoadAuthError(dbPath); got == nil || got.Kind != authErrorKindCorrupt || got.Message == "" { | ||
| t.Fatalf("LoadAuthError(corrupt) = %+v", got) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| package managedobserve | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "net" | ||
| "os" | ||
| "path/filepath" | ||
| "time" | ||
|
|
||
| "github.com/kontext-security/kontext-cli/internal/installation" | ||
| "github.com/kontext-security/kontext-cli/internal/managedconfig" | ||
| ) | ||
|
|
||
| // PrintStatus reports the managed-observe state for `kontext doctor`: | ||
| // which managed config (if any) this machine resolves, the installation | ||
| // identity, whether the daemon is reachable, the self-serve LaunchAgent, and | ||
| // any token-rejection breadcrumb the daemon left behind. | ||
| func PrintStatus(out io.Writer) { | ||
| fmt.Fprintln(out, "Managed observe:") | ||
|
|
||
| loaded, err := managedconfig.Load() | ||
| if errors.Is(err, managedconfig.ErrNotManaged) { | ||
| fmt.Fprintln(out, " config: not configured (run `kontext setup` to connect this Mac to a workspace)") | ||
| return | ||
| } | ||
| if err != nil { | ||
| fmt.Fprintf(out, " config: ERROR %v\n", err) | ||
| return | ||
| } | ||
|
|
||
| fmt.Fprintf(out, " config: %s (%s)\n", loaded.Path, describeScope(loaded.Scope)) | ||
| fmt.Fprintf(out, " organization: %s\n", loaded.Config.OrganizationID) | ||
|
|
||
| identityPath := installationPathForScope(loaded.Scope) | ||
| if state, err := installation.LoadFile(identityPath); err == nil { | ||
| fmt.Fprintf(out, " installation: %s\n", state.InstallationID) | ||
| } else { | ||
| fmt.Fprintf(out, " installation: not created yet (%s)\n", identityPath) | ||
| } | ||
|
|
||
| // Resolve the token through the daemon's exact read path: a locked or | ||
| // missing keychain item is THE silent killer under launchd, and "daemon: | ||
| // not running" alone points the user in the wrong direction. | ||
| ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | ||
| defer cancel() | ||
| if _, err := managedconfig.ResolveInstallToken(ctx, loaded.Config.Credentials.InstallTokenRef); err == nil { | ||
| fmt.Fprintf(out, " install token: readable (%s)\n", loaded.Config.Credentials.InstallTokenRef) | ||
| } else { | ||
| fmt.Fprintf(out, " WARNING: install token is not readable (%v) — the agent cannot stream; re-run `kontext setup` or unlock your login keychain\n", err) | ||
| } | ||
|
|
||
| if conn, err := net.DialTimeout("unix", DefaultSocketPath(), 500*time.Millisecond); err == nil { | ||
| conn.Close() | ||
| fmt.Fprintln(out, " daemon: running") | ||
| } else { | ||
| fmt.Fprintln(out, " daemon: not running (it starts with your next Claude Code session)") | ||
| } | ||
|
|
||
| // Self-serve installs have a user LaunchAgent; MDM installs manage theirs | ||
| // under /Library. Having BOTH scopes on one Mac deserves a callout — the | ||
| // system config wins and the user agent should be removed. | ||
| if home, err := os.UserHomeDir(); err == nil && home != "" { | ||
| userPlist := filepath.Join(home, "Library", "LaunchAgents", DefaultLaunchdLabel+".plist") | ||
| if _, err := os.Lstat(userPlist); err == nil { | ||
| fmt.Fprintf(out, " launch agent: %s\n", userPlist) | ||
| if loaded.Scope == managedconfig.ScopeSystem { | ||
| fmt.Fprintln(out, " WARNING: this Mac is organization-managed but a self-serve agent is also installed; run `kontext setup --uninstall` to remove it") | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // The LaunchAgent runs the daemon without --db, so the breadcrumb always | ||
| // sits next to the default database. A custom --db (dev-only hidden flag) | ||
| // is invisible here — acceptable for a diagnostics readout. | ||
| if authErr := LoadAuthError(DefaultDBPath()); authErr != nil { | ||
| switch authErr.Kind { | ||
| case "startup": | ||
| fmt.Fprintf(out, " WARNING: the agent failed to start — %s (%s)\n", authErr.Message, authErr.At) | ||
| case authErrorKindCorrupt: | ||
| fmt.Fprintf(out, " WARNING: auth breadcrumb is unreadable — %s\n", authErr.Message) | ||
| default: | ||
| detail := "" | ||
| if authErr.Status > 0 { | ||
| detail = fmt.Sprintf(" (HTTP %d, %s)", authErr.Status, authErr.At) | ||
| } | ||
| fmt.Fprintf(out, " WARNING: hosted ingest is failing — install token rejected%s; run `kontext setup` with a new token from the dashboard\n", detail) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func describeScope(scope managedconfig.Scope) string { | ||
| switch scope { | ||
| case managedconfig.ScopeSystem: | ||
| return "system, managed by your organization" | ||
| case managedconfig.ScopeUser: | ||
| return "user, installed by kontext setup" | ||
| case managedconfig.ScopeEnv: | ||
| return "env override" | ||
| default: | ||
| return string(scope) | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.