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
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "sourcegraph",
"description": "Search and read code in a Sourcegraph service at pinned commits, and register or maintain its repositories, through MCP or the sourcegraph CLI.",
"version": "0.5.1",
"version": "0.6.0",
"author": {
"name": "context4ai"
},
Expand Down
2 changes: 1 addition & 1 deletion cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@c4a/sourcegraph",
"version": "0.5.1",
"version": "0.6.0",
"description": "Command-line client for Sourcegraph: search and read code at pinned commits, register and manage repositories, personal and site settings.",
"license": "MIT",
"type": "module",
Expand Down
2 changes: 1 addition & 1 deletion cli/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ const C: Record<string, Command> = {
return jsonOutput ? out : `Token ${key.name}: ${scopeText(out)}`;
}
const r = await ctx.client.call('/auth/api-keys', { query: { limit: 100 } });
return jsonOutput ? r : table((r.items || []).map((k: any) => ({ id: k.id, name: k.name, prefix: k.key_prefix, scope: scopeText(k), created: k.created_at, expires: k.expires_at })), ['id', 'name', 'prefix', 'scope', 'created', 'expires']);
return jsonOutput ? r : table((r.items || []).map((k: any) => ({ id: k.id, name: k.name, kind: k.temporary ? 'temporary, read-only' : 'personal', prefix: k.key_prefix, scope: scopeText(k), created: k.created_at, expires: k.expires_at })), ['id', 'name', 'kind', 'prefix', 'scope', 'created', 'expires']);
} },
tags: { usage: `tags tags on repositories you can see, with counts
tags rename <old> <new> rename on every repository with the tag (you must manage all of them, or be a site administrator); token scopes follow`, summary: 'List and rename repository tags', run: async (ctx, a) => {
Expand Down
2 changes: 1 addition & 1 deletion cli/src/version.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const VERSION = '0.5.1';
export const VERSION = '0.6.0';
20 changes: 18 additions & 2 deletions config/deployment.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package deployment
import (
_ "embed"
"encoding/json"
"strings"
)

//go:embed deployment.json
Expand Down Expand Up @@ -36,11 +37,26 @@ type Defaults struct {
// The website's sites; the rest of the profile is read by the website and
// the CLI build.
Sites []struct {
ID string `json:"id"`
URL string `json:"url"`
ID string `json:"id"`
URL string `json:"url"`
Aliases []string `json:"aliases,omitempty"`
} `json:"sites"`
}

// SiteAddresses are the API base addresses of every configured site, aliases
// included (the CLI's SOURCEGRAPH_URL form, without a trailing slash).
func (d Defaults) SiteAddresses() []string {
var out []string
for _, s := range d.Sites {
for _, raw := range append([]string{s.URL}, s.Aliases...) {
if raw != "" {
out = append(out, strings.TrimSuffix(raw, "/"))
}
}
}
return out
}

func Load() Defaults {
var value Defaults
if err := json.Unmarshal(raw, &value); err != nil {
Expand Down
23 changes: 22 additions & 1 deletion docs/interfaces.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,13 +140,34 @@ Personal API keys are created from a signed-in user's settings. A key can prepar

Manual preparation is paced per repository across the website, HTTP and MCP. A request identical to a queued or running job (same group, kind and revision) returns that job and adds no queue load. Any other new request within 30 seconds of the repository's last accepted manual request returns `429 RATE_LIMITED` with `Retry-After`; one request queuing every monorepo group is a single request. Scheduled work is not paced.

### Temporary CLI tokens

An agent that only has MCP configured (address and personal token in its MCP settings) can let a command line next to it call the HTTP API as the same user, read-only, without the token passing through the model:

1. The agent calls the MCP tool `authorize_cli` (optional `client`, a display name up to 64 bytes, default `command line`). It returns `{code, expires_at, host, exchange_path}`: `code` starts with `sgc_`, is valid for 10 minutes and single use, and only its digest is stored. `host` is the API base of the address this MCP request came in on (the MCP URL without `/mcp`), the same form as `SOURCEGRAPH_URL`, e.g. `https://context4ai.org/sourcegraph`, or the origin alone when the service is served at the site root. It comes from the configured origin (or the matched extra public site) plus the external route prefix. A request forwarded by another site's `forward_hosts` reports the address the caller used only when a trusted proxy (loopback or `SOURCEGRAPH_TRUSTED_PROXIES`) delivered it, `X-Forwarded-Host` has a single value and that host plus this site's route prefix is one of the `sites` addresses in `config/deployment.json`; otherwise the configured address. `exchange_path` is `/auth/cli/exchange`, relative to `host`.
2. The command line sends `POST <host><exchange_path>` with `{"code":"…"}`, without signing in, and receives `{token, expires_at, max_expires_at, idle_seconds, scope:{tags, exclude_public}}`. The code is deleted in the same step.
3. It calls the HTTP API below the same `host` with `Authorization: Bearer <token>`.

Only a personal token's MCP connection can authorize: without a token `authorize_cli` answers `401 LOGIN_REQUIRED`, and temporary tokens' connections do not list it. Each user may authorize 30 times a minute (`429 RATE_LIMITED` with `retry_after_seconds`) and hold 20 unexpired temporary tokens (`429 TEMPORARY_TOKEN_LIMIT`, checked again on exchange). The exchange accepts 20 requests a minute per client address and 3000 in total (`429 RATE_LIMITED` with `Retry-After: 60`); an unknown, used or expired code, or one whose personal token was deleted or expired or whose owner was disabled, answers `400 INVALID_CODE`; an invalid body (unknown fields or trailing data included) answers `400 INVALID_REQUEST`.

A temporary token is a personal token of the same owner with these properties:

- `temporary` and `read_only` are true and `parent_id` names the authorizing personal token. Its scope (`tags`, `exclude_public`) is copied from that token at exchange and cannot be changed (`PATCH` answers `400 TEMPORARY_TOKEN_SCOPE_FIXED`; the website hides the visibility button). Its name is `CLI · <client> · temporary · MM-DD HH:MM`; only the digest is stored, so it cannot be copied from the token list.
- `expires_at` is 3 hours after the exchange. An admitted use more than 5 minutes after the last extension extends it to `min(now + 3 hours, max_expires_at)`; `max_expires_at` is 24 hours after the exchange. Refused requests (such as `TOKEN_READ_ONLY`) do not extend it. After 3 idle hours or the cap it answers `401`, and the record is removed (MongoDB: TTL index on `max_expires_at`; SQL: the hourly cleanup of expired rows).
- Read-only: retrieval routes, MCP and contents preparation (`kind: "content"`; MCP `prepare` with `content_only: true`). Everything else, including personal settings (tokens, code source tokens), other `/auth` routes, site settings, repository management, full preparation and sync or index, answers `403 TOKEN_READ_ONLY`. HTTP preparation checks repository management and reader preparation first, so a caller allowed neither gets `403 REPOSITORY_MANAGEMENT_DENIED` for other kinds.
- It never carries site administration, even when the owner is an administrator. Contents preparation takes the manager path when the owner manages the repository and the reader path otherwise; its limits are counted with the owner.
- Its MCP connection has the retrieval tools and, where the owner may prepare, `prepare` (contents only); no management tools and no `authorize_cli`.
- Deleting or rescoping the parent token, or renaming a tag in its scope, deletes its temporary tokens; disabling the owner disables them with every other token. These changes apply at once on the instance that made them and within 60 seconds elsewhere.

`GET /sourcegraph/auth/api-keys` lists `temporary`, `read_only`, `parent_id` and `max_expires_at` for every token; the website labels temporary tokens and lets their owner delete them; `sourcegraph tokens` shows a `kind` column. The service logs `cli_token_authorized` and `cli_token_exchanged`. `GET /v1/capabilities` lists `cli-authorization`.

### Command-line client `sourcegraph`

`npm i -g @c4a/sourcegraph` installs `sourcegraph`, a fuller client that also registers and manages repositories, personal tokens and site settings. `sourcegraph login` signs in through the website and stores a 90-day personal token; `sourcegraph --help` lists every command. See [cli/README.md](../cli/README.md). The agent skill in [skills/sourcegraph](../skills/sourcegraph/SKILL.md) teaches agents to use MCP or this CLI: `npx skills add context4ai/sourcegraph --skill sourcegraph`.

## Remote reads

For clients that update knowledge without a checkout. `GET /v1/capabilities` lists `diff-metadata`, `blob`, `blobs`, `scope-availability`, `directories` and `prepare-content` in `Operations`, plus `prepare-content-reader` while readers may prepare contents (below). These operations never run read plugins; paths are relative to the repository root, and in monorepo mode a path must lie inside a registered path group (link expansions do not count). They use the same authentication as search and read.
For clients that update knowledge without a checkout. `GET /v1/capabilities` lists `diff-metadata`, `blob`, `blobs`, `scope-availability`, `directories` and `prepare-content` in `Operations`, plus `prepare-content-reader` while readers may prepare contents (below) and `cli-authorization` (an MCP-only caller can give its command line a temporary read-only token for these operations; see [Temporary CLI tokens](#temporary-cli-tokens)). These operations never run read plugins; paths are relative to the repository root, and in monorepo mode a path must lie inside a registered path group (link expansions do not count). They use the same authentication as search and read.

- **Metadata-only diff:** `diff` with `"NamesOnly": true` (MCP `names_only`) runs `git diff-tree` only: `Path/ChangeKind/OldOID/NewOID/OldMode/NewMode`, up to 1000 per page, no prepared contents needed. Missing trees answer `409` (`SCOPE_NOT_READY` or `CONTENT_NOT_READY`); more than 8 MiB of output answers `422 DIFF_TOO_LARGE`. Patch diffs keep 1–100 per page; a patch over its budget returns its leading whole lines with `PatchTruncated`.
- **Raw file:** `POST /v1/repo/blob` with `{"Revision","Path"}` returns `application/octet-stream`, the bytes of `git cat-file blob <commit>:<path>`, with `X-Sourcegraph-Blob-OID`, `X-Sourcegraph-Commit` and `X-Sourcegraph-Kind` (`file` or `symlink`). Both raw reads repeat their media type in `X-Sourcegraph-Content-Type` (use it when a proxy rewrites `Content-Type`) and send `X-Content-Type-Options: nosniff`; read the body as bytes. Symlinks are not followed; a path below a symlinked directory is `404 FILE_NOT_FOUND`. Other codes: `422 NOT_A_FILE`, `413 FILE_TOO_LARGE` (above `max_blob_bytes`, default 8 MiB), `503 GIT_OBJECT_NOT_HYDRATED` (retryable), `409 CONTENT_NOT_READY`.
Expand Down
178 changes: 178 additions & 0 deletions internal/httpserver/cli_token.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
package httpserver

import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net"
"net/http"
"net/netip"
"net/url"
"strings"

"github.com/context4ai/sourcegraph/internal/config"
"github.com/context4ai/sourcegraph/internal/contract"
"github.com/context4ai/sourcegraph/internal/identity"
"github.com/context4ai/sourcegraph/internal/sso"
)

// Temporary command-line tokens (sso/cli_tokens.go): the MCP tool
// authorize_cli returns a one-time code and this site's addresses; the
// command line exchanges the code here, without signing in, for a temporary
// read-only personal token.
const (
cliTokenExchange = Prefix + cliExchangePath
// cliExchangePath is the exchange below the API base address (host).
cliExchangePath = "/auth/cli/exchange"
)

// readOnlyRoute lists what a read-only token may call: retrieval, MCP (whose
// connection offers only retrieval and content preparation) and content
// preparation (the handler checks kind=content).
func readOnlyRoute(r *http.Request) bool {
return retrievalRoute(r) || r.URL.Path == Prefix+"/mcp" || (r.Method == "POST" && r.URL.Path == Prefix+"/api/admin/v1/repo/prepare")
}

const siteFrozen = "This site is read-only while it moves to its new address; changes are not accepted here."

func tokenReadOnly() error {
return contract.Fail("TOKEN_READ_ONLY", "This temporary token is read-only: it may search, read and prepare content only.", 403)
}

// limitActor is whom request limits count: a read-only token counts with its
// owner, so several temporary tokens do not multiply the owner's limits.
func limitActor(ctx context.Context) string {
if identity.ReadOnlyToken(ctx) {
return "sso:" + identity.UserID(ctx)
}
return identity.Actor(ctx)
}

type cliHostKey struct{}

// withCLIHost records the API base address (the CLI's SOURCEGRAPH_URL form)
// the request came in on; authorize_cli returns it as host.
func withCLIHost(ctx context.Context, base string) context.Context {
return context.WithValue(ctx, cliHostKey{}, base)
}

// cliHost is the API base the caller used. own is the base this site's
// trusted configuration gives the request (origin plus external route
// prefix). A request forwarded from another address of this deployment —
// forward_hosts sets X-Forwarded-Host to the host the caller used — answers
// with that address instead, but only when a trusted proxy (loopback or
// trusted_proxy_cidrs) delivered it and the address, with own's path, is one
// of the deployment's configured sites (known): a client cannot make the
// command line send its code anywhere else. X-Forwarded-Proto is not read:
// the forwarding site itself is reached over plain HTTP from its entry,
// and every configured site address is https. Otherwise own.
func cliHost(r *http.Request, own string, proxies []netip.Prefix, known []string) string {
own = strings.TrimSuffix(own, "/")
forwarded := strings.ToLower(strings.TrimSpace(r.Header.Get("X-Forwarded-Host")))
if forwarded == "" || strings.ContainsAny(forwarded, ",/ ") || len(r.Header.Values("X-Forwarded-Host")) != 1 {
return own
}
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
host = r.RemoteAddr
}
peer, err := netip.ParseAddr(host)
if err != nil || !(peer.Unmap().IsLoopback() || trustedProxy(peer, proxies)) {
return own
}
u, err := url.Parse(own)
if err != nil {
return own
}
candidate := "https://" + forwarded + u.Path
for _, k := range known {
if candidate == k {
return candidate
}
}
return own
}

// authorizeCLI answers the MCP tool for an authenticated personal token.
func authorizeCLI(ctx context.Context, auth *sso.Handler, limits *websiteLimits, log *slog.Logger, c config.Config, client string) (any, error) {
if c.ReadOnly {
return nil, contract.Fail("SITE_FROZEN", siteFrozen, 503)
}
if auth == nil || identity.UserID(ctx) == "" {
return nil, contract.Fail("LOGIN_REQUIRED", "Authorizing a command line requires a personal token: sign in on the website, create a personal token in user settings, and send it from your MCP configuration as the header Authorization: Bearer <token>.", 401)
}
if identity.ReadOnlyToken(ctx) {
return nil, tokenReadOnly()
}
// Counted per user: several personal tokens do not multiply the limit.
if !limits.allow("sso:"+identity.UserID(ctx), "authorize-cli", 30, 3000) {
return nil, contract.FailRetryAfter("RATE_LIMITED", "Too many authorizations; retry after one minute.", 429, 60)
}
ctx, err := recheck(ctx)
if err != nil {
return nil, err
}
grant, err := auth.AuthorizeCLI(ctx, client)
switch {
case errors.Is(err, sso.ErrTokenReadOnly):
return nil, tokenReadOnly()
case errors.Is(err, sso.ErrTemporaryKeyLimit):
return nil, contract.Fail("TEMPORARY_TOKEN_LIMIT", "You already hold the maximum number of temporary tokens; revoke one in User settings or wait until one expires.", 429)
case errors.Is(err, sso.ErrNotFound):
return nil, contract.Fail("AUTHENTICATION_REQUIRED", "The token is no longer valid.", 401)
case err != nil:
return nil, contract.Fail("AUTH_STORAGE_UNAVAILABLE", "Authentication storage is unavailable; retry.", 503)
}
host, _ := ctx.Value(cliHostKey{}).(string)
log.Info("cli_token_authorized", "user", grant.UserID, "parent_id", grant.ParentID, "client", grant.Client, "code", grant.Digest)
return map[string]any{"code": grant.Code, "expires_at": grant.Expires, "host": host, "exchange_path": cliExchangePath}, nil
}

// cliExchange serves POST /auth/cli/exchange {code}.
func cliExchange(w http.ResponseWriter, r *http.Request, auth *sso.Handler, log *slog.Logger, readOnly bool, from string) {
w.Header().Set("Cache-Control", "no-store")
if readOnly {
// The freeze wraps the site outside this handler; apply it here too.
writeError(w, "", 503, "SITE_FROZEN", siteFrozen)
return
}
if auth == nil {
writeError(w, "", 404, "SSO_DISABLED", "Sign-in is not configured on this site.")
return
}
if r.Method != "POST" {
w.Header().Set("Allow", "POST")
writeError(w, "", 405, "METHOD_NOT_ALLOWED", "Use POST.")
return
}
var body struct {
Code string `json:"code"`
}
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 2048))
decoder.DisallowUnknownFields()
var trailing any
if decoder.Decode(&body) != nil || body.Code == "" || decoder.Decode(&trailing) != io.EOF {
writeError(w, "", 400, "INVALID_REQUEST", "Send the code returned by authorize_cli.")
return
}
key, err := auth.ExchangeCLICode(r.Context(), body.Code)
switch {
case errors.Is(err, sso.ErrInvalidCLICode):
writeError(w, "", 400, "INVALID_CODE", "The code is unknown, used or expired; call authorize_cli again.")
return
case errors.Is(err, sso.ErrTemporaryKeyLimit):
writeError(w, "", 429, "TEMPORARY_TOKEN_LIMIT", "You already hold the maximum number of temporary tokens; revoke one in User settings or wait until one expires.")
return
case err != nil:
writeError(w, "", 503, "API_KEY_STORAGE_UNAVAILABLE", "The token could not be created; retry with a new code.")
return
}
log.Info("cli_token_exchanged", "user", key.UserID, "token_id", key.ID, "from", from)
tags := key.Tags
if tags == nil {
tags = []string{}
}
writeJSON(w, 200, map[string]any{"token": key.Key, "expires_at": key.Expires, "max_expires_at": key.MaxExpires, "idle_seconds": int(sso.TemporaryKeyIdle.Seconds()), "scope": map[string]any{"tags": tags, "exclude_public": key.ExcludePublic}})
}
Loading